使用深度名称向量作为索引替换嵌套列表 [英] Replacing nested list using a vector of names of depths as an index
问题描述
获取一个简单的嵌套列表L
:
Take a simple nested list 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
以及一个向量,该向量为我要从L
中选择的每个部分提供一系列深度:
And a vector giving a series of depths for each part I want to select from L
:
sel <- c("lev1","lev2")
索引时我想要的结果是:
The result I want when indexing is:
L[["lev1"]][["lev2"]]
#[1] "bit1" "bit2"
我可以像这样使用Reduce
进行概括:
Which I can generalise using Reduce
like so:
Reduce(`[[`, sel, init=L)
#[1] "bit1" "bit2"
现在,我想扩展此逻辑以进行替换,例如:
Now, I want to extend this logic to do a replacement, like so:
L[["lev1"]][["lev2"]] <- "new val"
,但是我对如何生成递归[[
选择的方式感到很困惑,这使得我也可以对其进行赋值.
, but I am genuinely stumped as to how to generate the recursive [[
selection in a way that will allow me to then assign to it as well.
推荐答案
为什么你不能这样做
L[[sel]] <- "new val"
好吧,如果您想做很多事,那么
您仍然可以将Reduce
与modifyList
一起使用,或者可以使用[[<-
.这是modifyList
的示例:
well if you want to do the long way then
You could still use Reduce
with modifyList
or you could use [[<-
. Here is an example with modifyList
:
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
这篇关于使用深度名称向量作为索引替换嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!