How to manipulate NULL elements in a nested list?

前端 未结 5 975
说谎
说谎 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 14:08

    This is a hack, but as far as hacks go, I think I'm somewhat happy with it.

    lna <- eval(parse(text = gsub("NULL", "NA", deparse(l))))
    
    str(lna)
    #> List of 3
    #> $ : logi NA
    #> $ : num 1
    #> $ :List of 3
    #> ..$ : num 2
    #> ..$ : logi NA
    #> ..$ :List of 2
    #> .. ..$ : num 3
    #> .. ..$ : logi NA
    

    Update:

    If for some reason you needed "NULL" as a character entry in the list (corner case, much?) you can still use the above hack since it replaces the contents of the string, not the quotes, thus it just requires another step

    l2 <- list(
      NULL,
      1,
      list(
        2,
        "NULL",
        list(
          3,
          NULL
        )
      )
    )
    
    lna2   <- eval(parse(text = gsub("NULL", "NA", deparse(l2))))
    lna2_2 <- eval(parse(text = gsub('\\"NA\\"', '\"NULL\"', deparse(lna2))))
    
    str(lna2_2)
    #> List of 3
    #> $ : logi NA
    #> $ : num 1
    #> $ :List of 3
    #> ..$ : num 2
    #> ..$ : chr "NULL"
    #> ..$ :List of 2
    #> .. ..$ : num 3
    #> .. ..$ : logi NA 
    

提交回复
热议问题