Checking is.null in a case_when statement

As you get into parameter checking, beware that there are several things in R that have length 0 yet are not NULL. A non-exhaustive, off-the-top-of-my-head selection:

length(NULL) == 0
#> [1] TRUE
is.null(NULL)
#> [1] TRUE

length(logical(0)) == 0
#> [1] TRUE
is.null(logical(0))
#> [1] FALSE

length(character(0)) == 0
#> [1] TRUE
is.null(character(0))
#> [1] FALSE

length(numeric(0)) == 0
#> [1] TRUE
is.null(numeric(0))
#> [1] FALSE

length(list()) == 0
#> [1] TRUE
is.null(list())
#> [1] FALSE

length(data.frame()) == 0
#> [1] TRUE
is.null(data.frame())
#> [1] FALSE

# not to mention...
length(c(NA, NA, NA, NULL, NULL, logical(0)))
#> [1] 3

:cold_sweat: The R Inferno is one classic source of warnings about such gotchas.

P.S. Tiny friendly tip: around here we encourage people to format their code as code to make it easier to read. You can follow the instructions in this FAQ, or just use the little </> button at the top of the posting box. :grin:

5 Likes