I have a list of vectors in R:
[[1]]
[1] 1 2 3 4
[[2]]
[1] 7 9 1 4
[[3]]
[1] 8 2 1
[[4]]
[1] 8 9 0 7
And I want to make a dataframe out of them. The problem is, I can't simply use unlist and then reorganize, because not all the vectors are the same length – I want NAs in my dataframe when that happens. The final result should look like this:
Col1 Col2 Col3 Col4
1 2 3 4
7 9 1 4
8 2 1 NA
8 9 0 7
Is there a way to do this?
Using purrr you can do the following:
require(purrr)
L <- list(1:4, c(7,9,1,4), c(8,2,1), c(8,9,0,7))
map_df(L, ~as.data.frame(t(.)))
Which gives you:
V1 V2 V3 V4
1 1 2 3 4
2 7 9 1 4
3 8 2 1 NA
4 8 9 0 7
Base R approach:
clen <- vapply(L, length, integer(1))
mat <- matrix(NA, nrow = length(L), ncol = max(clen))
for(i in seq_along(L)){
mat[i, seq(1, clen[i])] <- L[[i]]
}
as.data.frame(mat)
Try this in base R (where ls is your list object):
data.frame(t(sapply(ls, function(x) x[1:max(lengths(ls))])))
Which given your data will give you:
# X1 X2 X3 X4
#1 1 2 3 4
#2 7 9 1 4
#3 8 2 1 NA
#4 8 9 0 7
In general, c(1:5)[1:7] will give you
#[1] 1 2 3 4 5 NA NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With