Reputation: 3486
I'm trying to handle NULL values using case_when, so that a value is returned when the value is null, otherwise, the object is returned as-is
h <- NULL
dplyr::case_when(
is_empty(h) ~ "This is null",
T ~ h)
> Error in value[[i]] : subscript out of bounds
I don't understand why the error: shouldn't the case_when
just output "This is null" and stop there?
Upvotes: 1
Views: 452
Reputation: 887088
According to ?case_when
A vector of length 1 or n, matching the length of the logical input or output vectors, with the type (and attributes) of the first RHS. Inconsistent lengths or types will generate an error.
Here NULL
doesn't have any length
> length(NULL)
[1] 0
Thus, it will result in inconsistent lengths (1 vs 0). By default, the TRUE
in case_when
returns NA
(and it will be based on the value type return of other expressions i.e. here it would be NA_character_
). So, we may simply use the case_when
without a TRUE
condition
> library(dplyr)
> library(rlang)
> h <- NULL
> case_when(is_empty(h) ~ "This is null")
[1] "This is null"
> h <- "hello"
> case_when(is_empty(h) ~ "This is null")
[1] NA
Upvotes: 1