[R] Is there an easier way to iterate over multiple data frames in R?
Jeff Newmiller
jdnewmil at dcn.davis.ca.us
Wed Nov 23 17:06:29 CET 2011
Whenever similar objects are to be handled with similar code, having the data frames stored in lists or even as one big data frame is preferred. If you can load them as such, half the complexity is addressed right there.
The for loop processing is usually wrapped up using base apply functions or "plyr" package functions. Those idioms are not necessarily faster than for loops, but they can wrap up some common split and assemble steps cleanly.
---------------------------------------------------------------------------
Jeff Newmiller The ..... ..... Go Live...
DCN:<jdnewmil at dcn.davis.ca.us> Basics: ##.#. ##.#. Live Go...
Live: OO#.. Dead: OO#.. Playing
Research Engineer (Solar/Batteries O.O#. #.O#. with
/Software/Embedded Controllers) .OO#. .OO#. rocks...1k
---------------------------------------------------------------------------
Sent from my phone. Please excuse my brevity.
Kaiyin Zhong <kindlychung at gmail.com> wrote:
>> for (d in paste('df', 1:3, sep='')) {
>+ assign(d, as.data.frame(replicate(3, rnorm(4))))
>+ }
>> dats = list(df1,df2,df3)
>> for (i in 1:length(dats)) {
>+ names(dats[[i]]) = c('w', 'l', 'h')
>+ }
>> dats
>[[1]]
> w l h
>1 1.24319239 -0.05543649 0.05409178
>2 0.05124331 -1.89346950 0.33896273
>3 -1.69686777 -0.35963008 -0.91720034
>4 1.30786112 -0.23953238 0.94139356
>
>[[2]]
> w l h
>1 -1.238519 -0.12352187 -1.2577607
>2 1.180469 2.38836107 2.9139199
>3 1.494369 -0.07088712 0.2372746
>4 1.942535 1.47911615 1.1431675
>
>[[3]]
> w l h
>1 1.0198692 -1.4222194 1.9486072
>2 0.3057461 1.7630326 -0.6501801
>3 -0.5576854 -1.1637263 -0.1782680
>4 0.6625268 0.6913202 0.9588915
>> i = 1
>> for (n in paste('df', 1:3, sep='')) {
>+ assign(n, dats[[i]])
>+ i = i+1
>+ }
>> df1
> w l h
>1 1.24319239 -0.05543649 0.05409178
>2 0.05124331 -1.89346950 0.33896273
>3 -1.69686777 -0.35963008 -0.91720034
>4 1.30786112 -0.23953238 0.94139356
>
> [[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list