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?