How to manipulate NULL elements in a nested list?

前端 未结 5 938
说谎
说谎 2020-12-16 13:19

I have a nested list containing NULL elements, and I\'d like to replace those with something else. For example:

l <- list(
  NULL,
  1,
  list(
    2,
           


        
5条回答
  •  一生所求
    2020-12-16 13:46

    This can also be done with rrapply() in the rrapply-package. Below are a few different ways we could replace the NULL elements in a nested list by NA values:

    library(rrapply)
    
    l <- list(
        NULL,
        1,
        list(
            2,
            NULL,
            list(
                3,
                NULL
            )
        )
    )
    
    ## replace NULL by NA using only f
    rrapply(l, f = function(x) if(is.null(x)) NA else x, how = "replace")
    #> [[1]]
    #> [1] NA
    #> 
    #> [[2]]
    #> [1] 1
    #> 
    #> [[3]]
    #> [[3]][[1]]
    #> [1] 2
    #> 
    #> [[3]][[2]]
    #> [1] NA
    #> 
    #> [[3]][[3]]
    #> [[3]][[3]][[1]]
    #> [1] 3
    #> 
    #> [[3]][[3]][[2]]
    #> [1] NA
    
    ## replace NULL by NA using condition argument
    rrapply(l, condition = is.null, f = function(x) NA, how = "replace")
    #> [[1]]
    #> [1] NA
    #> 
    #> [[2]]
    #> [1] 1
    #> 
    #> [[3]]
    #> [[3]][[1]]
    #> [1] 2
    #> 
    #> [[3]][[2]]
    #> [1] NA
    #> 
    #> [[3]][[3]]
    #> [[3]][[3]][[1]]
    #> [1] 3
    #> 
    #> [[3]][[3]][[2]]
    #> [1] NA
    
    ## replace NULL by NA using condition and deflt arguments 
    rrapply(l, condition = Negate(is.null), deflt = NA, how = "list")
    #> [[1]]
    #> [1] NA
    #> 
    #> [[2]]
    #> [1] 1
    #> 
    #> [[3]]
    #> [[3]][[1]]
    #> [1] 2
    #> 
    #> [[3]][[2]]
    #> [1] NA
    #> 
    #> [[3]][[3]]
    #> [[3]][[3]][[1]]
    #> [1] 3
    #> 
    #> [[3]][[3]][[2]]
    #> [1] NA
    

    We can also prune the NULL elements from the list altogether by setting how = "prune":

    ## keep only non-NULL elements
    rrapply(l, condition = Negate(is.null), how = "prune")
    #> [[1]]
    #> [1] 1
    #> 
    #> [[2]]
    #> [[2]][[1]]
    #> [1] 2
    #> 
    #> [[2]][[2]]
    #> [[2]][[2]][[1]]
    #> [1] 3
    

提交回复
热议问题