[R] Mutliple sets of data in one dataset....Need a loop?

Mario Valle mvalle at cscs.ch
Fri Jan 22 16:13:54 CET 2010


Great example Glen!
I want to add simply a small thing that could be useful to someone.

Suppose in your last step you want to change the line color for each chart.
Using a for loop it is simple to use the integer index to access the df.lst elements and
set the color:

   for(i in 1:length(df.lst)) plot(df.lst[i]$x, df.lst[i]$y, color=colors[i])

To do it 'lapply-style' use mapply:

   mapply(function(d, i) plot(d$x, d$y, color=colors[i]), dl, 1:length(dl))

Ciao!
	mario

Glen Sargeant wrote:
> One way to plot subsets of data identified by a grouping variable is to use
> lapply() on a list of subsets.  The approach is worth mentioning because
> similar tactics are useful for many problems. 
> 
> #List of unique values for grouping variable
> #that is not necessarily a factor
> names <- as.list(unique(df$Experiment))
> 
> #List of dataframes; 1 for each unique value of grouping variable
> df.lst <- lapply(names,function(name)subset(df,Experiment==name))
> 
> #Name components of the list
> #Not necessary in this case... but permits indexing by level
> #of the grouping variable
> names(df.lst) <- names
> 
> #Now you can use lapply() to carry out the same operation on
> #each component of your list.  For example, to send plots to
> #a pdf with 1 page for each component:
> 
> pdf("plot.pdf")
> lapply(df.lst,function(df)plot(df[,2],df[,3]))
> dev.off() 
> 
> 
> 
> 
> -----
> Glen Sargeant
> Research Wildlife Biologist

-- 
Ing. Mario Valle
Data Analysis and Visualization Group            | http://www.cscs.ch/~mvalle
Swiss National Supercomputing Centre (CSCS)      | Tel:  +41 (91) 610.82.60
v. Cantonale Galleria 2, 6928 Manno, Switzerland | Fax:  +41 (91) 610.82.82



More information about the R-help mailing list