Search code examples
rlistnestedassign

Replacing nested list using a vector of names of depths as an index


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

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"

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.


Solution

  • Why cant you just do

    L[[sel]] <- "new val"
    

    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