R 使用深度名称向量作为索引替换嵌套列表
取一个简单的嵌套列表R 使用深度名称向量作为索引替换嵌套列表,r,list,nested,assign,R,List,Nested,Assign,取一个简单的嵌套列表L: L <- list(lev1 = list(lev2 = c("bit1","bit2")), other=list(yep=1)) L #$lev1 #$lev1$lev2 #[1] "bit1" "bit2" # # #$other #$other$yep #[1] 1 sel <- c("lev1","lev2") 编制索引时我想要的结果是: L[["lev1"]][["lev2"]] #[1] "bit1" "bit2" 我可以用Reduce
L
:
L <- list(lev1 = list(lev2 = c("bit1","bit2")), other=list(yep=1))
L
#$lev1
#$lev1$lev2
#[1] "bit1" "bit2"
#
#
#$other
#$other$yep
#[1] 1
sel <- c("lev1","lev2")
编制索引时我想要的结果是:
L[["lev1"]][["lev2"]]
#[1] "bit1" "bit2"
我可以用Reduce
这样概括:
Reduce(`[[`, sel, init=L)
#[1] "bit1" "bit2"
现在,我想扩展这个逻辑来做一个替换,如下所示:
L[["lev1"]][["lev2"]] <- "new val"
L[[“lev1”][[“lev2”]]您可以通过连接所有内容来eval()
和parse()
。我不确定你能做到什么程度:
``` r
L <- list(lev1 = list(lev2 = c("bit1","bit2")), other=list(yep=1))
L
#> $lev1
#> $lev1$lev2
#> [1] "bit1" "bit2"
#>
#>
#> $other
#> $other$yep
#> [1] 1
sel <- c("lev1","lev2")
eval(parse(text = paste0('L', paste0('[["', sel, '"]]', collapse = ''), '<- "new val"')))
L
#> $lev1
#> $lev1$lev2
#> [1] "new val"
#>
#>
#> $other
#> $other$yep
#> [1] 1
``r
L$1列弗
#>$lev1$lev2
#>[1]“位1”“位2”
#>
#>
#>美元其他
#>$other$yep
#> [1] 1
sel$lev1
#>$lev1$lev2
#>[1]“新val”
#>
#>
#>美元其他
#>$other$yep
#> [1] 1
由(v0.3.0)创建于2019-11-25,为什么你不能这么做
L[[sel]] <- "new val"
很明显,我错过了一个把戏,因为事情太复杂了。我不认为L[[sel]]
会像预期的那样工作。从?list
-“[[”可以递归地应用于列表,因此,如果单个索引“I”是长度为“p”的向量,则“alist[[I]]”相当于“alist[[i1]]…[[ip]]”在列表中提供除最终索引结果以外的所有结果。”唯一的区别似乎是,L@latemail当你有一个空列表时,你不是在替换
,而是在创建一个新的值,这就是它会出错的原因。但是在替换时,你直接使用它,就像文档中所说的那样。只是觉得值得注意这个区别。
modifyList(L,Reduce(function(x,y)setNames(list(x),y),rev(sel),init = "new val"))
$lev1
$lev1$lev2
[1] "new val"
$other
$other$yep
[1] 1