向列表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
阿克伦

由于list“ A”和“ B”中相应元素的长度不相同,因此我们可以将其保留为a list一种方便的功能是Maplist“ A”和“ B”的相应元素执行此操作

lst <- Map(list, A, B)

如果我们要保持这个作为一个matrixNA垫的长度不等,一种选择是stri_list2matrixlibrary(stringi)输出将是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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章