I want to convert a list that has a list of numbers of varying lengths(1-4) for the values into an mx4 dataframe with NAs in place of missing values.
So far I was only able to row bind using: do.call(rbind, lapply(list, data.frame))
I want to convert a list that has a list of numbers of varying lengths(1-4) for the values into an mx4 dataframe with NAs in place of missing values.
So far I was only able to row bind using: do.call(rbind, lapply(list, data.frame))
You were close:
dat <- list(
x = c(0.9, 0.5, 0.6, 0.8),
y = c(0.5, 0.1),
z = c(0.3, 0.2, 0.5)
)
as.data.frame(do.call(rbind, lapply(dat, `length<-`, max(lengths(dat)))))
# V1 V2 V3 V4
# x 0.9 0.5 0.6 0.8
# y 0.5 0.1 NA NA
# z 0.3 0.2 0.5 NA
(If you really need names like 1num
, then you can do it manually. I suggest against leading names with a number, though, as that'll require you to backtick your $
accessors.)