如何在R列表中递归遍历所有键值对并修改值?

时间:2019-05-20 11:27:14

标签: r list replace

我想根据某些条件递归修改列表的值。

mylist = list(a = "test1", 
              b = list(bb = "test2", list(bbb = "test1")), 
              c = "test2")

如果值是 test1 ,我想修改该值并将其替换在此列表中或创建一个新列表。例如,如果修改是将 test1 替换为 best1 ,则结果列表应为

mylist = list(a = "best1", 
              b = list(bb = "test2", list(bbb = "best1")), 
              c = "test2")

在R中最干净的方法是什么?

2 个答案:

答案 0 :(得分:5)

您可以使用rapply

out <- rapply(mylist, function(x) replace(x, x == "test1", "best1"), how = "replace")

检查输出

identical(out, 
          list(a = "best1", 
               b = list(bb = "test2", list(bbb = "best1")), 
               c = "test2"))
# [1] TRUE

答案 1 :(得分:3)

编辑: 我的原始答案(如下)unlist s。但是,我们可以使用purrrplyr来实现类似列表的替换:

plyr::llply(purrr::flatten(mylist),
            function(x) ifelse(x=="test1","best1",x))

$a
[1] "best1"

$bb
[1] "test2"

[[3]]
    bbb 
"best1" 

$c
[1] "test2"

原始

我们可以使用:

lapply(Map(unlist,mylist),function(x) ifelse(x=="test1","best1",x))
$a
[1] "best1"

$b
     bb     bbb 
"test2" "best1" 

$c
[1] "test2"