Bind vectors across lists to single list of matrices
One option is to transpose
the list
of list
s, then reduce
the list
elements to a single dataset with cbind.fill
, get the transpose (t
) and assign the row names to NULL
library(tidyverse)
library(rowr)
list(list1, list2, list3) %>%
transpose %>%
map(~ reduce(.x, cbind.fill, fill = NA) %>%
t %>%
`row.names<-`(NULL))
#$a
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1 2 3 4 5
#[2,] 1 2 3 4 NA
#[3,] 1 2 3 NA NA
#$b
# [,1] [,2] [,3] [,4] [,5]
#[1,] 6 7 8 9 10
#[2,] 6 7 8 9 NA
#[3,] 6 7 8 NA NA
#$c
# [,1] [,2] [,3] [,4] [,5]
#[1,] 11 12 13 14 15
#[2,] 11 12 13 14 NA
#[3,] 11 12 13 NA NA
Or using base R
do.call(Map, c(f = function(...) {l1 <- list(...)
do.call(rbind, lapply(l1, `length<-`, max(lengths(l1))))},
mget(paste0("list", 1:3))))
a data.table
solution, just for fun:
plouf <- list(list1,list2,list3)
lapply(names(list1),function(name){
lapply(plouf,function(x){
as.data.table(t(x[[name]]))
}) %>%
rbindlist(.,fill =T) %>%
`colnames<-`(NULL)
}) %>% setNames(names(list1))
$a
1: 1 2 3 4 5
2: 1 2 3 4 NA
3: 1 2 3 NA NA
$b
1: 6 7 8 9 10
2: 6 7 8 9 NA
3: 6 7 8 NA NA
$c
1: 11 12 13 14 15
2: 11 12 13 14 NA
3: 11 12 13 NA NA
the first loop is on the list name. The second loop loop is on the list of list, and extract the element of each list, transpose it into a data.table with unique row, to be able to use rbindlist
which can fill missing columns.
without data.table
, so similar but less good than what akrun proposed:
library(plyr)
lapply(names(list1),function(name){
lapply(plouf,function(x){
t(x[[name]])%>%
as.data.frame
}) %>%
rbind.fill %>%
`colnames<-`(NULL)
}) %>% setNames(names(list1))
You may use 1. rapply
to adjust the length
s of the sublists, and 2. t(mapply)
to get the matrices by selecting with '[['
.
listn <- list(list1, list2, list3)
setNames(lapply(seq(listn), function(x)
t(mapply(`[[`, rapply(listn, `length<-`, value=5, how="list"), x))), names(el(listn)))
# $a
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 2 3 4 5
# [2,] 1 2 3 4 NA
# [3,] 1 2 3 NA NA
#
# $b
# [,1] [,2] [,3] [,4] [,5]
# [1,] 6 7 8 9 10
# [2,] 6 7 8 9 NA
# [3,] 6 7 8 NA NA
#
# $c
# [,1] [,2] [,3] [,4] [,5]
# [1,] 11 12 13 14 15
# [2,] 11 12 13 14 NA
# [3,] 11 12 13 NA NA
In case the lengths are unknown use this code:
max(rapply(listn, length))
# [1] 5