Hey Folks, Could somebody show me how to loop through a list of dataframes? I want to be able to generically access their elements and do something with them. For instance, instead of this: df1<- data.frame(x=(1:5),y=(1:5)); df2<- data.frame(x=(1:5),y=(1:5)); df3<- data.frame(x=(1:5),y=(1:5)); plot(df1$x,df1$y); plot(df2$x,df2$y); plot(df3$x,df3$y); I would like to do something like: (pseudocode) dfarray[1] = df1 dfarray[2] = df2 dfarray[3] = df3 for (each i in dfarray) { plot(i$x, i$y); } Can this be done in R? Thanks. Tripp -- View this message in context: http://www.nabble.com/Looping-through-a-list-of-objects---do-something...-tp15562391p15562391.html Sent from the R help mailing list archive at Nabble.com.
Duncan Murdoch
2008-Feb-19 19:08 UTC
[R] Looping through a list of objects & do something...
On 2/19/2008 1:51 PM, TLowe wrote:> Hey Folks, > > Could somebody show me how to loop through a list of dataframes? I want to > be able to generically access their elements and do something with them. > > For instance, instead of this: > > df1<- data.frame(x=(1:5),y=(1:5)); > df2<- data.frame(x=(1:5),y=(1:5)); > df3<- data.frame(x=(1:5),y=(1:5)); > plot(df1$x,df1$y); > plot(df2$x,df2$y); > plot(df3$x,df3$y); > > I would like to do something like: > (pseudocode) > dfarray[1] = df1 > dfarray[2] = df2 > dfarray[3] = df3 > for (each i in dfarray) { > plot(i$x, i$y); > } > > Can this be done in R?Yes, easily: dfarray <- list(df1, df2, df3) lapply(dfarray, function(i) plot(i$x, i$y)) Duncan Murdoch
On Tuesday 19 February 2008 (19:51:15), TLowe wrote:> Hey Folks, > > Could somebody show me how to loop through a list of dataframes? I want to > be able to generically access their elements and do something with them. > > For instance, instead of this: > > df1<- data.frame(x=(1:5),y=(1:5)); > df2<- data.frame(x=(1:5),y=(1:5)); > df3<- data.frame(x=(1:5),y=(1:5)); > plot(df1$x,df1$y); > plot(df2$x,df2$y); > plot(df3$x,df3$y); > > I would like to do something like: > (pseudocode) > dfarray[1] = df1 > dfarray[2] = df2 > dfarray[3] = df3 > for (each i in dfarray) { > plot(i$x, i$y); > }It's surprisingly simple: for(df in list(df1,df2,df3)) plot(df$x,df$y) Best, Martin
Possibly Parallel Threads
- looping through data frames in a workspace
- Best way/practice to create a new data frame from two given ones with last column computed from the two data frames?
- merging several dataframes from a list
- indexing into a data.frame using another data.frame that also contains values for replacement
- Multiple merge, better solution?