Dambo
Dambo

Reputation: 3486

How to handle objects with NULL values using case_when?

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

Answers (1)

akrun
akrun

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

Related Questions