我是R的新手,仍然试图绕过申请系列,而不是使用循环。
我有两个列表,一个是嵌套的,另一个不是,都由字符组成:
>lst1 <- list(c("ABC", "DEF", "GHI"), c("JKL", "MNO", "PQR"))
>lst2 <- c("abc", "def")
我想创建第三个列表,以便将lst2的每个元素作为lst1中相应子列表的最后一个元素附加。所需的输出如下所示:
>lst3
[[1]]
[1] "ABC" "DEF" "GHI" "abc"
[[2]]
[1] "JKL" "MNO" "PQR" "def"
到目前为止,我在R中的经验告诉我,如果没有明确地编写循环,可能有一种方法可以做到这一点。
答案 0 :(得分:4)
您可以使用与Map
完全相同的mapply(..., simplify = F)
:
Map(c, lst1, lst2)
[[1]]
[1] "ABC" "DEF" "GHI" "abc"
[[2]]
[1] "JKL" "MNO" "PQR" "def"
答案 1 :(得分:1)
如果您在lapply
向量的长度上应用函数,则绝对可以使用lst1
。这有效:
lapply(1:length(lst1),function(i) append(lst1[[i]],lst2[[i]]))
[[1]]
[1] "ABC" "DEF" "GHI" "abc"
[[2]]
[1] "JKL" "MNO" "PQR" "def"
答案 2 :(得分:0)
lapply
无法满足您的需求。您可以使用append
的循环执行此操作:
list1 <- list(c("ABC","DEF","GHI"),c("JKL","MNO","PQR"))
list2 <- c("abc","def")
listcomplete <- list(c("ABC","DEF","GHI","abc"),c("JKL","MNO","PQR","def"))
for (i in 1:length(list2)) {
list1[[i]] <- append(list1[[i]],list2[i])
}
结果:
> list1
[[1]]
[1] "ABC" "DEF" "GHI" "abc"
[[2]]
[1] "JKL" "MNO" "PQR" "def"