向列表R中的每个子列表添加向量

Bar*_*aby 3 r

我有两个具有相同结构的列表.我想将它们组合起来以产生以下所需的输出.

A <- list(c(1,2,3,2,1,4),c(7,3,1,2,2,1),c(2,3,7,2,2,8))
B <- list(c(2,1,3,2),c(3,1,5,2),c(2,4,5,1))

# Desired Output

[[1]]
    [1] 1 2 3 2 1 4
    [1] 2 1 3 2
[[2]]
    [1] 7 3 1 2 2 1
    [1] 3 1 5 2
[[3]]
    [1] 2 3 7 2 2 8
    [1] 2 4 5 1

# I have tried with the items beloww and nothing works as to produce the shown desired output. Would you happen to know on how to combine the two vectors as to produce the outcome below. 

c
cbind(A,B)
     A         B        
[1,] Numeric,6 Numeric,4
[2,] Numeric,6 Numeric,4
[3,] Numeric,6 Numeric,4

merge
append
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

由于list"A"和"B"中相应元素的长度不同,我们可以将其保持为a list.一个方便的功能是Maplist'A'和'B'的相应元素上执行此操作.

lst <- Map(list, A, B)
Run Code Online (Sandbox Code Playgroud)

如果我们要保持这个作为一个matrixNA垫的长度不等,一种选择是stri_list2matrixlibrary(stringi).输出将是a matrix,但我们需要将character输出转换回来numeric

library(stringi)
lst1 <- lapply(lst, stri_list2matrix, byrow=TRUE)
lapply(lst1, function(x) matrix(as.numeric(x),nrow=2))
#[[1]]
#      [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    1    2    3    2    1    4
#[2,]    2    1    3    2   NA   NA

#[[2]]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    7    3    1    2    2    1
#[2,]    3    1    5    2   NA   NA

#[[3]]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    2    3    7    2    2    8
#[2,]    2    4    5    1   NA   NA
Run Code Online (Sandbox Code Playgroud)