1

I have the following list:

my_list = list(list(NULL, '4'), NULL, 5)

str(my_list)
#> List of 3
#>  $ :List of 2
#>   ..$ : NULL
#>   ..$ : chr "4"
#>  $ : NULL
#>  $ : num 5

I would like to learn how to replace the NULL elements with NA. Is it possible to do this using rapply? Here is my attempt:

my_list = list(list(NULL, '4'), NULL, 5)

rapply(my_list, function(x) NA, how = "replace", classes = 'NULL')
#> [[1]]
#> [[1]][[1]]
#> NULL
#> 
#> [[1]][[2]]
#> [1] "4"
#> 
#> 
#> [[2]]
#> NULL
#> 
#> [[3]]
#> [1] 5

I would like rapply to replace NULL elements, hence I specified classes = 'NULL' and how = 'replace'. But as you can see in the output above, the NULL elements are not replaced.

I can achieve the desired output by recursively applying purrr::modify as follows:

library(purrr)

my_list = list(list(NULL, '4', list('y', NULL)), NULL, 5)
str(my_list)
#> List of 3
#>  $ :List of 3
#>   ..$ : NULL
#>   ..$ : chr "4"
#>   ..$ :List of 2
#>   .. ..$ : chr "y"
#>   .. ..$ : NULL
#>  $ : NULL
#>  $ : num 5

replaceNULL <- function(x) {

  modify_if(x, is.list, replaceNULL, .else = ~ifelse(is.null(.), NA, .))

}
replaceNULL(my_list)
#> [[1]]
#> [[1]][[1]]
#> [1] NA
#> 
#> [[1]][[2]]
#> [1] "4"
#> 
#> [[1]][[3]]
#> [[1]][[3]][[1]]
#> [1] "y"
#> 
#> [[1]][[3]][[2]]
#> [1] NA
#> 
#> 
#> 
#> [[2]]
#> [1] NA
#> 
#> [[3]]
#> [1] 5

Created on 2019-07-03 by the reprex package (v0.3.0.9000)

However, I was wondering if someone could shed some light on why the rapply isn't working?

user51462
  • 1,658
  • 2
  • 13
  • 41
  • 3
    Possible duplicate https://stackoverflow.com/questions/38950005/how-to-manipulate-null-elements-in-a-nested-list/ – Ronak Shah Jul 03 '19 at 11:00
  • Thanks @Ronak, I seemed to have missed that one when I searched for similar questions. I don't mind deleting mine but I was hoping someone could help me understand why the `rapply` wasn't working. – user51462 Jul 03 '19 at 11:40
  • No need to delete. If you think the post answers your question I'll mark it as duplicate or else we can keep it as open. – Ronak Shah Jul 03 '19 at 11:48
  • Cheers, the answers in the other post don't get into why the `rapply` failed so I'd prefer to keep this one open. – user51462 Jul 03 '19 at 23:20
  • In the question linked by @Ronak Shah, there is also this link to https://stackoverflow.com/questions/7170264/why-do-rapply-and-lapply-handle-null-differently – Aurèle Jul 04 '19 at 10:24

0 Answers0