【问题标题】:Add each element from one list to the corresponding element of the another list in R将一个列表中的每个元素添加到 R 中另一个列表的相应元素
【发布时间】:2020-01-14 05:12:49
【问题描述】:

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

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 的长度。

【问题讨论】:

    标签: r list element add


    【解决方案1】:

    我们可以使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多