向列表R中的每个子列表添加向量
我有两个结构相同的列表。我想将它们结合起来,以产生以下所需的输出向列表R中的每个子列表添加向量,r,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]]
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
A您的“期望输出”不是很清楚。列表的第一个元素中有什么?这是另一张单子吗
您可以尝试使用mapply
,并更改FUN
以获得不同的输出格式:
mapply(FUN = list, A, B, SIMPLIFY = FALSE)
这将在列表中为您提供一个列表。由于“a”和“B”中相应的列表
元素的长度不同,我们可以将其保留在列表中。一个方便的功能是Map
在相应的list
元素“A”和“B”上执行此操作
lst <- Map(list, A, B)
您可以使用Map(list,A,B)
,因为“A”和“B”中的对应元素具有不同的长度。我不知道您可以在函数外部使用mappy Map并生成预期的输出这是预期的输出吗?
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