Home > Net >  Combine elements of a list in R [duplicate]
Combine elements of a list in R [duplicate]

Time:09-26

I have a list having 2 elements with 4 columns each.

I'd like to combine 2 elements to have one element/dataframe with 4 columns and 6 rows.

Any suggestions for this?

My example, given

# create a list
l1 <- list(df1 = data.frame(n1 = c(2,2,0), n2 = c(2,1,1), n3 = c(0,1,1), n4 = c(0,1,1)),
           df2 = data.frame(n1 = c(1,6,0), n2 = c(2,1,8), n3 = c(0,2,1), n4 = c(0,7,1))) 

CodePudding user response:

You can use bind_rows from dplyr, here an example with your data:

# Data

l1 <- list(df1 = data.frame(n1 = c(2,2,0), n2 = c(2,1,1), n3 = c(0,1,1), n4 = c(0,1,1)),
           df2 = data.frame(n1 = c(1,6,0), n2 = c(2,1,8), n3 = c(0,2,1), n4 = c(0,7,1))) 


library(dplyr)

bind_rows(l1)

  n1 n2 n3 n4
1  2  2  0  0
2  2  1  1  1
3  0  1  1  1
4  1  2  0  0
5  6  1  2  7
6  0  8  1  1
  •  Tags:  
  • r
  • Related