I have multiple data.frames that I want to rbind together using R. I also have a character vector with the names of each of these data.frames. What I'm looking to do is use this character vector to determine which data.frames to bind together.
For example, I have 5 similar data.frames below and I want to bind the first 3 data.frames using the character list somehow. Is it possible to use this character vector to rbind these data.frames?
# Create List
l <- c( "list1","list2","list3")
# Data Frames
list1 <- data.frame(
Name="Test1",
Data="Test1"
)
list2 <- data.frame(
Name="Test2",
Data="Test2"
)
list3 <- data.frame(
Name="Test3",
Data="Test3"
)
list4 <- data.frame(
Name="Test4",
Data="Test4"
)
list5 <- data.frame(
Name="Test5",
Data="Test5"
)
# Rbind data.frames ?
dat <- rbind( l[1], l[2], l[3] )
dat
# Loop and rbind ?
df <- data.frame()
for( i in 1:length(l)) {
print( l[i] )
df[i] <- rbind( df, l[i] )
}
CodePudding user response:
result = do.call(rbind, args = mget(l))
should work.
mget
returns a list()
of the objects from your global environment. do.call(fun, list)
is how we write fun(list[[1]], list[[2]], ...)
.
As a side-note, I'd suggest not using the word "list" to refer to vectors--save it for list
class objects.
CodePudding user response:
You can use mget
dplyr::bind_rows
:
library(dplyr)
bind_rows(mget(l))
Name Data
1 Test1 Test1
2 Test2 Test2
3 Test3 Test3
CodePudding user response:
Using data.table
library(data.table)
rbindlist(mget(l))
CodePudding user response:
you can use
join_all(list(df1,df2,df3,df4), by = 'commun_character_vector', type = 'full')