[R] create separate plots by factors
David M Smith
david at revolution-computing.com
Tue Aug 11 00:16:18 CEST 2009
If you want to use foreach to do the looping, you can use the "isplit"
function to create an iterator returning blocks of data, each block
being the data for one site:
> require(foreach)
> site.data <- read.table("isplit-data.txt",header=T) # data copied from email
> sites <- isplit(site.data,site.data$site)
You can see how the iterator works with nextElem. The value is a list
with two elements "value" (the block) and "key" (the site name, as a
list):
> nextElem(sites)
$value
site year peak
1 ALBEN 5 101529.6
2 ALBEN 10 117483.4
3 ALBEN 20 132960.9
4 ALBEN 50 153251.2
5 ALBEN 100 168647.8
6 ALBEN 200 184153.6
7 ALBEN 500 204866.5
$key
$key[[1]]
[1] "ALBEN"
Now you can use foreach to loop over your data frame, without a
separate split operation:
sites <- isplit(site.data,site.data$site)
foreach(site=sites) %dopar% {
pdf(paste(site$key[[1]],".pdf",sep=""))
plot(site$value$year,site$value$peak,main=site$key[[1]])
dev.off()
}
On the data you showed, this creates three files: ALBEN.pdf, ALDER.pdf
and AMERI.pdf, each with a scatterplot of peak by year.
If your 300 plots take a non-trivial amount of time to produce, and
speed is a concern, you could even parallelize the production on a
multiprocessor system (Mac/Unix only) with registerDoMC().
Hope this helps,
# David Smith
On Fri, Aug 7, 2009 at 12:05 PM, Ingrid Tohver<itohver at u.washington.edu> wrote:
> Hello,
> I am attempting to create several plots based on "site" (~300 total) and am
> having trouble with the code. I simply want to create a plot using the code,
> plot(year, peak), for the following dataset. I would like for each site to
> be plotted on a separate page and the plots saved in a directory. Would a
> "foreach" loop work? I tried a "by" statement, but it doesn't seem to work
> with plotting functions.
> I would really appreciate any leads.
> Ingrid
>
> site year peak
> ALBEN 5 101529.6
> ALBEN 10 117483.4
> ALBEN 20 132960.9
> ALBEN 50 153251.2
> ALBEN 100 168647.8
> ALBEN 200 184153.6
> ALBEN 500 204866.5
> ALDER 5 6561.3
> ALDER 10 7897.1
> ALDER 20 9208.1
> ALDER 50 10949.3
> ALDER 100 12287.6
> ALDER 200 13650.2
> ALDER 500 15493.6
> AMERI 5 43656.5
> AMERI 10 51475.3
> AMERI 20 58854.4
> AMERI 50 68233.3
> AMERI 100 75135.9
> AMERI 200 81908.3
>
>
> Ingrid M Tohver
> Research Scientist, Climate Impacts Group
> University of Washington
--
David M Smith <david at revolution-computing.com>
Director of Community, REvolution Computing www.revolution-computing.com
Tel: +1 (206) 577-4778 x3203 (San Francisco, USA)
Check out our upcoming events schedule at www.revolution-computing.com/events
More information about the R-help
mailing list