Search code examples
rvectornested

Apply function to a certain element of a nested list


I want to substract one from a particular element of a nested list. How should I do that?

This is my nested list I want to one from positive values of bar vector (check first is it is positive)

x <- list(a = list(foo = 1:8, bar = 3:4), b = list(baz = 5:6))

I was thinking about map function.

Thank you!


Solution

  • You could write a recursive function:

    mod_at <- function(x, name, FUN){
      if(name %in% names(x)){ 
        x[[name]] <- FUN(x[[name]])
        x
      }
      else if(is.list(x))lapply(x, mod_at, name, FUN)
      else x
    }
    

    Now use that to modify the list:

    mod_at(x, "bar", function(x)ifelse(x>0, x-1, x))
    
    $a
    $a$foo
    [1] 1 2 3 4 5 6 7 8
    
    $a$bar
    [1] 2 3
    
    
    $b
    $b$baz
    [1] 5 6
    

    You could use the function the way you want:

    mod_at(x, "baz", sqrt)
    
    $a
    $a$foo
    [1] 1 2 3 4 5 6 7 8
    
    $a$bar
    [1] 3 4
    
    
    $b
    $b$baz
    [1] 2.236068 2.449490