append a list element-wise to elements of a nested list in R

纵然是瞬间 提交于 2020-02-15 10:20:08

问题


I'm new to R and still trying to get my head around the apply family instead of using loops.

I have two lists, one nested, the other not, both composed of characters:

>lst1 <- list(c("ABC", "DEF", "GHI"), c("JKL", "MNO", "PQR"))
>lst2 <- c("abc", "def")

I would like to create a third list such that each element of lst2 is appended as the last element of the respective sublist in lst1. The desired output looks like this:

>lst3
[[1]]
[1] "ABC" "DEF" "GHI" "abc"

[[2]]
[1] "JKL" "MNO" "PQR" "def"

My experience thus far in R tells me there likely is a way of doing this without writing a loop explicitly.


回答1:


You can use Map which does exactly what mapply(..., simplify = F) do:

Map(c, lst1, lst2)
[[1]]
[1] "ABC" "DEF" "GHI" "abc"

[[2]]
[1] "JKL" "MNO" "PQR" "def"



回答2:


You can definitely use lapply if you apply your function over the length of your lst1 vector. This works:

lapply(1:length(lst1),function(i) append(lst1[[i]],lst2[[i]]))

[[1]]
[1] "ABC" "DEF" "GHI" "abc"

[[2]]
[1] "JKL" "MNO" "PQR" "def"



回答3:


lapply will not do what you need. You can use a loop with append to do this:

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])
}

Results:

> list1
[[1]]
[1] "ABC" "DEF" "GHI" "abc"

[[2]]
[1] "JKL" "MNO" "PQR" "def"


来源:https://stackoverflow.com/questions/37846320/append-a-list-element-wise-to-elements-of-a-nested-list-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!