简体   繁体   中英

Is there a way to bind multiple dataframes by a named list?

forgive me if this has been asked before but i'm unable to put the right search terms in to find anyone else having this problem.

Using loops, I've created a list of the names of dataframes. What I'm trying to do is use reference that list so rbind appends the corresponding dataframes together. Below is an example of what I'm trying to do:

list <- list("df1","df2","df3") #represents the list of names of the dataframes 
all_df <- rbind(list)

The above just appends together the names of the dataframes, rather than the dataframes themselves. I've also tried:

all_df <- rbindlist(list)

and

all_df <- do.call(what = rbind, args = list)

but with no luck. All the advice I can find seem to refer to a list of dataframes rather than a list of names of dataframes.

Please help! I'm pulling my hair out over this because I know the solution is probably really simple!

If I understand correctly, you have a character vector with the names of the objects you want to bind. Your goal is to bind multiple dataframes into asingle dataframe using the "vector of names".

May I suggest to use mget() function to convert your character vector into actual object's names? This does not require to make a list.

Please see the code below:

# dummy data to test it
df1 <- head(mtcars, 2)
df2 <- head(mtcars, 3)
df3 <- head(mtcars, 4)

# your "vector of names"
lst.names <- list("df1","df2","df3") # the output of your loop
df.names <- do.call(rbind, lst.names)[, 1] # change the list to a character vector

# this seems to work
do.call(rbind, mget(df.names)) 

The output:

> do.call(rbind, mget(df.names)) 
                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
df1.Mazda RX4      21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
df1.Mazda RX4 Wag  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
df2.Mazda RX4      21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
df2.Mazda RX4 Wag  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
df2.Datsun 710     22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
df3.Mazda RX4      21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
df3.Mazda RX4 Wag  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
df3.Datsun 710     22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
df3.Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1

Example:

library(rlist)

textdfs <- list('mtcars', 'mtcars', 'mtcars')
mylist <- lapply(textdfs, function(x) eval(parse(text=x)))
bigdf <- list.rbind(mylist)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM