Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combining data.frames in R based off a character list

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] )
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading