How to convert a list consisting of vector of different lengths to a usable data frame in R?
One liner with plyr
plyr::ldply(word.list, rbind)
try this:
word.list <- list(letters[1:4], letters[1:5], letters[1:2], letters[1:6])
n.obs <- sapply(word.list, length)
seq.max <- seq_len(max(n.obs))
mat <- t(sapply(word.list, "[", i = seq.max))
the trick is, that,
c(1:2)[1:4]
returns the vector + two NAs
Another option is stri_list2matrix
from library(stringi)
library(stringi)
stri_list2matrix(l, byrow=TRUE)
# [,1] [,2] [,3] [,4]
#[1,] "a" "b" "c" NA
#[2,] "a2" "b2" NA NA
#[3,] "a3" "b3" "c3" "d3"
NOTE: Data from @juba's post.
Or as @Valentin mentioned in the comments
sapply(l, "length<-", max(lengths(l)))
You can do something like this :
## Example data
l <- list(c("a","b","c"), c("a2","b2"), c("a3","b3","c3","d3"))
## Compute maximum length
max.length <- max(sapply(l, length))
## Add NA values to list elements
l <- lapply(l, function(v) { c(v, rep(NA, max.length-length(v)))})
## Rbind
do.call(rbind, l)
Which gives :
[,1] [,2] [,3] [,4]
[1,] "a" "b" "c" NA
[2,] "a2" "b2" NA NA
[3,] "a3" "b3" "c3" "d3"
You could also use rbindlist()
from the data.table package.
Convert vectors to data.table
s or data.frame
s and transpose them (not sure if this reduces speed a lot) with the help of lapply()
. Then bind them with rbindlist()
- filling missing cells with NA.
require(data.table)
l = list(c("a","b","c"), c("a2","b2"), c("a3","b3","c3","d3"))
dt = rbindlist(
lapply(l, function(x) data.table(t(x))),
fill = TRUE
)