r - 如何修改多级嵌套 R 列表中的元素?

标签 r nested-loops nested-lists

我需要做的是替换 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功能 ?

最佳答案

你可以从purrrmodify函数开始

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(.)))))

对于替换,我们将使用 stringrstr_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/

相关文章:

R highcharter -- 将图表保存到外部 iframe 的 html 文件吗?

r - 在分组数据上使用工具提示时,ggvis 中的值消失

html - Bootstrap 嵌套列表的一致样式

python - 如何在 Python 中逐行打印嵌套列表中的项目?

r - 如何在 ggplot2 中制作 x 轴和 y 轴之间的间隙以及突出的刻度线

c++ - 什么是 R 保存终端标志?

linux - 根据 header 分割 fasta 文件

c++ - 嵌套的基于范围的 for 循环

c - 如何跳出嵌套循环?

scala - scala 中的 "unlist"(例如展平一系列序列的序列......)