【问题标题】:Add elements from a list to multiple other nested lists将列表中的元素添加到多个其他嵌套列表
【发布时间】:2017-08-07 09:07:07
【问题描述】:

我有一个列表列表,如下:

my_list = list(list(a=1,b=2),list(a=1,b=2),list(a=1,b=2))

我有一个向量b_new,长度和length(my_list)一模一样:

b_new = c(3,4,5)

我想用 b 中的值顺序覆盖 my_list 的 b 元素,所以预期的输出是:

my_list = list(list(a=1,b=3),list(a=1,b=4),list(a=1,b=5))

我显然可以在 for 循环中做到这一点:

for(i in 1:length(b_new))
{
  my_list[[i]]$b=b_new[i]
}

但我想知道是否有一种方法可以在没有 for 循环的情况下执行此操作,例如使用 mapply?

【问题讨论】:

  • 我想知道通过其map* 函数的purrr 解决方案将如何。也许我稍后会试一试

标签: r list


【解决方案1】:

这仍然是一个循环,但以下内容会做到这一点:

Map(`[<-`, my_list, "b", b_new)
# or more pleasantly named:
Map(replace, my_list, "b", b_new)

str(Map(`[<-`, my_list, "b", b_new))
#List of 3
# $ :List of 2
#  ..$ a: num 1
#  ..$ b: num 3
# $ :List of 2
#  ..$ a: num 1
#  ..$ b: num 4
# $ :List of 2
#  ..$ a: num 1
#  ..$ b: num 5

【讨论】:

  • 谢谢,也许效率不高(?),但它看起来更干净。我试图理解这个陈述,但是当我输入 help(Map) 时,我看到:Map(f, ...),其中 ... 是向量。您愿意解释一下您陈述中的“b”是如何工作的吗?
  • @florian 这基本上扩展为一遍又一遍地执行 listitem["b"]
猜你喜欢
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-15
相关资源
最近更新 更多