Reputation: 3
I have multiple identical dataframes: X1, X2, ..., X32
example of one dataframe:
> X1
value
1 3300320
I would like to have juste one dataframe like that:
> XTotal
value X
1 3300320 1
2 345098 2
...
32 34355 32
I tried with a for loop and paste("X", i, sep=""), rbind, etc. but each time I got a list of string like that:
> listDF
1 "X1"
2 "X2"
...
32 "X32"
So, I can't call properly each dataframe to put their values in the XTotal dataframe...
I'm a little lost, any idea?
Thanks in advance!
Upvotes: 0
Views: 1939
Reputation: 115392
Never grow an object in a loop. This is highly inefficient as it will copy the entire object every time.
to create a list of the data.frames use get
and lapply
or mget
dflist <- mget(paste('X', 1:32), envir = parent.frame())
# also valid
# dflist <- lapply(paste('X', 1:32), get)
# to combine them
DFlist <- do.call('rbind', dflist)
# or, faster
library(data.table)
DFlist <- rbindlist(dflist)
If the data.frames do not have the same columns / order of columns use rbind.fill
from plyr
library(plyr)
DFlist <- rbind.fill(dflist)
There really isn't any need to create dflist
explicity
Any of the following would also work
rbind.fill(mget(paste('X', 1:32), envir = parent.frame()))
rbindlist(mget(paste('X', 1:32), envir = parent.frame()))
do.call(rbind, mget(paste('X', 1:32), envir = parent.frame()))
Upvotes: 1