I keep coming to this question and usually end up adapting the current answers to my need.
Current answers either mess up with types of variables, or do not handle well proper list of lists (note the plural).
tl;dr: use the following:
This works when each element in listHolder contains a column of the dataframe
df <- data.frame(lapply(listHolder, function(x) Reduce(c, x)))
This works when each element in listHolder contains a row of the dataframe
df <- do.call(rbind, lapply(listHolder, data.frame))
Minimal Working Example (list elements are columns)
The following code provides a MWE and reviews other answers. The #General Approach
is what I would recommend to use.
listHolder <- list(
A = rep(list(1, 2), 80),
B = rep(c(3, 4), 80),
C = rep(c("a", "b"), 80),
D = rep(list("c", "d"), 80),
E = rep(as.POSIXct(10485849600, origin = "1582-10-14", tz = "GMT"), 160)
)
# @Noha's Answer
data1 <- as.data.frame(matrix(unlist(listHolder), nrow=length(unlist(listHolder[1]))))
# Try this (mess up with types)
str(data1)
# @Camilo's Answer
data2 <- data.frame(do.call(cbind, listHolder))
# Try this (each column becomes a list)
str(data2)
# General Approach
data3 <- data.frame(lapply(listHolder, function(x) Reduce(c, x)))
str(data3)
Minimal Working Example (list elements are rows)
This code should be used when each element in the list is supposed to hold a row in the dataframe
listHolder <- list(
row1 = list(name = "foo", surname = "bar", age = 90),
row2 = list(name = "foo", surname = "foo", age = 29),
row3 = list(name = "bar", surname = "foo", age = 45),
row4 = list(name = "bar", surname = "bar", age = 10)
)
# A simple rbind won't work (each column is still a list)
data1 <- do.call(rbind, listHolder)
str(data1)
# General Approach (now it's better)
data2 <- do.call(rbind, lapply(listHolder, data.frame))
str(data2)