将一个列表中的每个元素添加到 R 中另一个列表的相应元素

Add each element from one list to the corresponding element of the another list in R

我有两个列表,长度相同,我想将第二个列表的第一个元素添加到第一个列表的第一个元素,依此类推。 这是我的例子: # 模拟数据是

m1<- matrix(c(2,3,4,5), nrow = 2, ncol = 2)
m2<- matrix(c(1,2 ,3,4,5,6), nrow = 2, ncol = 3)
m3<- matrix(c(1,10,6,8 ,3,4,5,6), nrow = 4, ncol = 2)
 m4<-matrix(c(2,5,9,11), nrow = 2,ncol = 2)
 list1 <- list(list(x= c(m1,m4, m3), y=c(m1,m2,m3), z=c(m1,m2,m4)),list(x= c(m4,m2, m3), y=c(m1,m2,m4), z=c(m2,m2,m3)),list(x= c(m1,m2, m3), y=c(m1,m2,m3), z=c(m1,m2,m3)))
list2<- list(list(f=m4),list( g=m4),list( h=m2))

实现我想要的代码

list1[[1]][[4]]<- list2[[1]][[1]]
list1[[2]][[4]]<- list2[[2]][[1]]
list1[[3]][[4]]<- list2[[3]][[1]]
names(list1[[1]])<- c("x","y","z","f")
names(list1[[2]])<- c("x","y","z","g")
names(list1[[3]])<- c("x","y","z","h")

#我的问题是如何用循环或 lapply 做同样的事情,因为我的实际数据很长,不仅列出了 3 的长度。

我们可以使用Map,将每个列表对应的元素进行组合。

Map(c, list1, list2)

#[[1]]
#[[1]]$x
# [1]  2  3  4  5  2  5  9 11  1 10  6  8  3  4  5  6

#[[1]]$y
# [1]  2  3  4  5  1  2  3  4  5  6  1 10  6  8  3  4  5  6

#[[1]]$z
# [1]  2  3  4  5  1  2  3  4  5  6  2  5  9 11

#[[1]]$f
#     [,1] [,2]
#[1,]    2    9
#[2,]    5   11
#....

类似于 purrr

中的 map2
purrr::map2(list1, list2, c)