ABB ABB - 2 months ago 7
R Question

R-Is there a way to combine list with variable number of rows to a dataframe

If there is a list of unequal number of row vectors(all the vectors have 3 columns) like below:

>typicalList

[[1]]
col1 col2 col3
1 12 10 ABC
2 54 87 DEF

[[2]]
col1 col2 col3
1 64 9 GHI
2 59 6 JKL
3 43 4 PST


Is it possible to have a dataframe from the above list with a new column called
newColumn
that looks like below:

newColumn col1 col2 col3
1 12 10 ABC
1 54 87 DEF
2 64 9 GHI
2 59 6 JKL
2 43 4 PST


Used
ldply(typicallist,rbind)
but that splits all the rows belonging to a vector in the original list giving 5 independent records in the dataframe. Is it possible to have the dataframe like above that suggests (through
newColumn
) field that first two records are derived from the first vector of the list and the remaining three from the second? Is there any better way to realize this in R?

Data

typicalList <- list(structure(list(col1 = c(12L, 54L), col2 = c(10L, 87L), col3 = c("ABC",
"DEF")), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c("1",
"2")), structure(list(col1 = c(64L, 59L, 43L), col2 = c(9L, 6L,
4L), col3 = c("GHI", "JKL", "PST")), .Names = c("col1", "col2",
"col3"), class = "data.frame", row.names = c("1", "2", "3")))

Answer

We can use rbindlist from data.table with the idcol argument

library(data.table)
rbindlist(typicalList, idcol = "newColumn")
#   newColumn col1 col2 col3
#1:         1   12   10  ABC
#2:         1   54   87  DEF
#3:         2   64    9  GHI
#4:         2   59    6  JKL
#5:         2   43    4  PST

Or use bind_rows with .id from dplyr

library(dplyr)
bind_rows(typicalList, .id = "newColumn")
#  newColumn col1 col2 col3
#1         1   12   10  ABC
#2         1   54   87  DEF
#3         2   64    9  GHI
#4         2   59    6  JKL
#5         2   43    4  PST
Comments