r - 追加两个列表列表的列表

标签 r list append lapply

我有两个列表如下:

list1 <- list(c(`0` = 0L, `25` = 0L, `100` = 1L, `250` = 1L, `500` = 1L, 
                `1000` = 1L, Infinity = 3L), c(`0` = 0L, `25` = 0L, `100` = 1L, 
                                               `250` = 1L, `500` = 1L, Infinity = 4L))

list2 <- list(c(`0` = 0L, `25` = 0L, `100` = 0L, `250` = 2L, `500` = 1L, 
                `1000` = 1L, Infinity = 3L), c(`0` = 0L, `25` = 0L, `100` = 1L, 
                                               `250` = 1L, `500` = 1L, Infinity = 4L))

我想将 list2[[1]] append 到 list1[[1]] 并 append list2[[2]]list1[[2]]。这样:

list_out <- list(c(`0` = 0L, `25` = 0L, `100` = 1L, `250` = 1L, `500` = 1L, 
                `1000` = 1L, Infinity = 3L, `0` = 0L, `25` = 0L, `100` = 0L, `250` = 2L, `500` = 1L, 
                `1000` = 1L, Infinity = 3L), c(`0` = 0L, `25` = 0L, `100` = 1L, 
                                               `250` = 1L, `500` = 1L, Infinity = 4L, `0` = 0L, `25` = 0L, `100` = 1L, 
                                               `250` = 1L, `500` = 1L, Infinity = 4L))

谁能帮我解释一下我该怎么做?

最佳答案

您可以使用lapplyc()

lapply(1:length(list1), function(x) c(list1[[x]], list2[[x]]))

或者maplyappendc:

mapply(append, list1, list2)

输出

[[1]]
       0       25      100      250      500     1000 Infinity        0 
       0        0        1        1        1        1        3        0 
      25      100      250      500     1000 Infinity 
       0        0        2        1        1        3 

[[2]]
       0       25      100      250      500 Infinity        0       25 
       0        0        1        1        1        4        0        0 
     100      250      500 Infinity 
       1        1        1        4 

检查它是否与您的list_out相同:

identical(lapply(1:length(list1), function(x) c(list1[[x]], list2[[x]])), list_out)
[1] TRUE

identical(mapply(append, list1, list2), list_out)
[1] TRUE

关于r - 追加两个列表列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72159588/

相关文章:

javascript - div在创建jquery对象中的作用

r - 如何操作 R 中的 ggplot 以在 lhs 上为角度 = 45 长 x 轴标签留出额外空间?

r - 如何组合两个具有相同CRS和非重叠区域的sf对象?

r - col2rgb(d) : invalid color name in tweenr 中的错误

python - 在两个列表中搜索项目

python - 检查列表是否具有完全重复的元素(即没有唯一元素)

java - 将字符串参数转换为 StringBuffer

r - 通过最小化 R 中的方差对数据进行分组

list - 如何在 Common Lisp 中从现有列表中设置某些内容

list - Prolog 在列表中追加列表