我需要做的是替换 type
的所有值嵌套列表第 4 层上的向量 a
通过transcodification
上的相应人员tibble 并为列表的其余部分保持相同的结构:
a = list(
a1 = list(
b1 = list(
c1 = list(
type = c(1,3),
attribute1 = runif(3,0,1),
attribute2 = list(d = rpois(1,1))
),
c2 = list(
type = c(2,3,6),
attribute1 = runif(3,0,1),
attribute2 = list(d = rpois(1,1))
)
),
b2 = list("foo")
),
a2 = list(
b1 = list(
c3 = list(
type = c(5),
attribute1 = runif(3,0,1),
attribute2 = list(d = rpois(1,1))
),
c4 = list(
type = c(2,3,6),
attribute1 = runif(3,0,1),
attribute2 = list(d = rpois(1,1))
)
),
b2 = list("foo")
),
a3 = list(
b1 = list(
c5 = list(
type = c(6),
attribute1 = runif(3,0,1),
attribute2 = list(d = rpois(1,1))
),
c6 = list(
type = c(1,2,3,5),
attribute1 = runif(3,0,1),
attribute2 = list(d = rpois(1,1))
)
),
b2 = list("foo")
)
)
transcodification = tibble(origin = c(1,2,3,4,5,6),
replacement = c("Peter","Jake","Matthew","Suzan","Christina","Margot"))
是否可以使用 purrr
功能 ?
最佳答案
你可以从purrr
的modify
函数开始
modify_depth(a, 3, ~map(., ~str_replace_all(., transcodification %>% pull(2) %>% set_names(1:length(.)))))
$a1
$a1$b1
$a1$b1$c1
$a1$b1$c1$type
[1] "Peter" "Matthew"
$a1$b1$c1$attribute1
character(0)
$a1$b1$c1$attribute2
character(0)
$a1$b1$c2
$a1$b1$c2$type
[1] "Jake" "Matthew" "Margot"
$a1$b1$c2$attribute1
character(0)
$a1$b1$c2$attribute2
character(0)
$a1$b2
$a1$b2[[1]]
$a1$b2[[1]][[1]]
[1] "foo"
但这将分别在 b2 中引入额外的列表层。
如果 "type"
总是在第一棵树上,那么您可以尝试不做任何进一步的转换
modify_depth(a, 3, ~modify_at(.,1, ~str_replace_all(., transcodification %>% pull(2) %>% set_names(1:length(.)))))
或在每个数字向量上
modify_depth(a, 3, ~modify_if(., is.numeric, ~str_replace_all(., transcodification %>% pull(2) %>% set_names(1:length(.)))))
对于替换,我们将使用 stringr
的 str_replace_all
,而替换是使用这样的命名向量完成的:
transcodification %>% pull(2) %>% set_names(1:length(.))
1 2 3 4 5 6
"Peter" "Jake" "Matthew" "Suzan" "Christina" "Margot"
关于r - 如何修改多级嵌套 R 列表中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68558427/