2015-09-14 44 views
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 
+1

你可以有'地图(列表中,A,B)'作为“A”和“B”的对应元素不同的长度 – akrun

+0

不知道你可以在函数外使用map函数并产生预期的输出 – Barnaby

+0

这是预期的输出吗? – akrun

回答

4

由于'A'和'B'中对应的list元素的长度不相同,我们可以将其保存在list中。一个方便的功能是Map在'A'和'B'的相应list元素上做到这一点。

lst <- Map(list, A, B) 

如果我们想与NA保持这个作为matrix垫不等长,一种选择是从library(stringi)stri_list2matrix。输出将是一个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 
1

你'想要的输出'不是很清楚。列表中的第一个元素是什么?这是另一个列表吗?

你可以尝试使用mapply,并更改FUN得到不同的输出格式:

mapply(FUN = list, A, B, SIMPLIFY = FALSE) 

,让你列表中的列表。