在 R 中追加列表元素

问题描述 投票:0回答:1

我有两个大的、有序的整数列表。我希望

length
[i]
位置处的整数
hello
等于
length
[i]
位置处的
bye

这是一个模拟我的数据集的简化的可重现示例:

c1<- c(0,1,0,1,1,1,0,0) |> as.integer()
c2<- c(0,1,0) |> as.integer()
c3<- c(1,1,1,0,0,0,0,0,0) |> as.integer()
c4<- c(0,1,0,1,0,0,0,1,0,1) |> as.integer()
c5<- c(0,1,0,1,0,0,0,0) |> as.integer()
c6 <-  c(1,1,1,0,0) |> as.integer()

hello<- list(c1, c2, c3)
bye<- list(c4,c5,c6)

列出输出:

hello
[[1]]
[1] 0 1 0 1 1 1 0 0

[[2]]
[1] 0 1 0

[[3]]
[1] 1 1 1 0

bye
[[1]]
 [1] 0 1 0 1 0 0 0 1 0 1

[[2]]
[1] 0 1 0 1 0 0 0 0

[[3]]
[1] 1 1 1 0 0

我希望扩展的相关列表元素的值为

appended
,值为 0。单个列表元素的所需输出如下所示:

hello[[2]]
[1] 0 1 0 0 0 0 0 0

bye[[2]]
[1] 0 1 0 1 0 0 0 0

到目前为止,我已经尝试了带有附加语句的 for 循环,但我无法开始工作。

我认为

lapply
purrr::map
会提供一个更简洁的解决方案,但我仍在尝试了解 R 中的函数式编程。任何帮助将不胜感激。

r list if-statement integer append
1个回答
0
投票

对于单向填充(

hello
项目的长度根据相关
bye
项目的长度进行调整),您可以使用

library(purrr)

hello2 <- map2(hello, bye, function(h,b) {
  if(length(b)>length(h)) {
    h <- append(h, rep(0, length(b)-length(h)))
  } else {
    h
  }
})

map2
在两个列表上成对迭代并为每对调用给定函数。在这里,我们检测是否需要调整长度,然后附加所需数量的零。

© www.soinside.com 2019 - 2024. All rights reserved.