更改嵌套列表中的值

Change values in nested list

假设这个嵌套列表

df <- list(list(a = 1, b = 2, c = 3, d = 4, e = 5), 
           list(a = 1, b = 2, c = 3, d = 4, e = 5), 
           list(a = 1, b = 2, c = 3, d = 4, e = 5), 
           list(a = 1, b = 2, c = 3, d = 4, e = 5), 
           list(a = 1, b = 2, c = 3, d = 4, e = 5))

现在,我想更改列表索引 c(2, 5) 中变量 d 的一些值。 一个预期的输出是:

list(list(a = 1, b = 2, c = 3, d = 4, e = 5), 
     list(a = 1, b = 2, c = 3, d = 50, e = 5), 
     list(a = 1, b = 2, c = 3, d = 4, e = 5), 
     list(a = 1, b = 2, c = 3, d = 4, e = 5), 
     list(a = 1, b = 2, c = 3, d = 50, e = 5))

另一个输出包含 d 的不同值,例如 c(50, 100)

我已经问过类似的问题 ,但我不知道如何在不使用 for 循环的情况下转换建议的函数以获取每个索引的结果。首选使用管道的方法。

我们可以使用Map

df[c(2, 5)] <- Map(function(x, y) {x$d <- y; x}, df[c(2, 5)], c(50, 100))

使用purrr:

按名称分配

library(purrr)

df[c(2, 5)] <- map2(df[c(2, 5)], c(50, 100), ~ list_modify(.x, d = .y))

如果加载库 magrittr 可以简化为:

library(purrr)
library(magrittr)

df[c(2, 5)] %<>% map2(c(50, 100), ~ list_modify(.x, d = .y))

按元素位置赋值

使用assign_in:

df[c(2, 5)] %<>% map2(c(50, 100), ~ assign_in(.x, 4, .y))

不像Akrun的那样优雅的解决方案,但也许你可以编写一个函数来select嵌套列表中的一个元素值并重写为一个新值,然后使用lapply()来让它在“元列表”上工作,并覆盖已更改的嵌套列表。这是一个例子

##Example Data##
df <- list(list(a = 1, b = 2, c = 3, d = 4, e = 5), 
           list(a = 1, b = 2, c = 3, d = 4, e = 5), 
           list(a = 1, b = 2, c = 3, d = 4, e = 5), 
           list(a = 1, b = 2, c = 3, d = 4, e = 5), 
           list(a = 1, b = 2, c = 3, d = 4, e = 5))

##Function to extract an element from nested list and rewrite to a new value##
List_fxn<-function(LIST, ELEMENT, NEW_VALUE){
  LIST[names(LIST)==ELEMENT]<-NEW_VALUE
  return(LIST)
}

##Run the function on nested lists 2 and 5, then overwrite nested lists 2 and 5 in df##
df[c(2,5)]<-lapply(df[c(2,5)], List_fxn, ELEMENT = "d", NEW_VALUE = 100)

##View the results##
print(df)

您可以像下面那样尝试[<-

df[c(2,5)] <- Map(`[<-`,df[c(2,5)],"d",c(50,100))

这给出了

> df
[[1]]
[[1]]$a
[1] 1

[[1]]$b
[1] 2

[[1]]$c
[1] 3

[[1]]$d
[1] 4

[[1]]$e
[1] 5


[[2]]
[[2]]$a
[1] 1

[[2]]$b
[1] 2

[[2]]$c
[1] 3

[[2]]$d
[1] 50

[[2]]$e
[1] 5


[[3]]
[[3]]$a
[1] 1

[[3]]$b
[1] 2

[[3]]$c
[1] 3

[[3]]$d
[1] 4

[[3]]$e
[1] 5


[[4]]
[[4]]$a
[1] 1

[[4]]$b
[1] 2

[[4]]$c
[1] 3

[[4]]$d
[1] 4

[[4]]$e
[1] 5


[[5]]
[[5]]$a
[1] 1

[[5]]$b
[1] 2

[[5]]$c
[1] 3

[[5]]$d
[1] 100

[[5]]$e
[1] 5