To expand a little bit on @nwerth's answer, part of the problem is that grepl() returns a logical vector of length 0 when its x is NULL. For comparison:
library(tidyverse)
x <- NULL
y <- 3
length(is.null(x))
#> [1] 1
length(grepl("word", x, ignore.case = TRUE))
#> [1] 0
length(y > 2)
#> [1] 1
case_when(
is.null(x) ~ "I'm NULL",
grepl("word", x, ignore.case = TRUE) ~ "I'm a word",
TRUE ~ "other"
)
#> character(0)
case_when(
is.null(x) ~ "I'm NULL",
y > 2 ~ "Big y",
TRUE ~ "other"
)
#> [1] "I'm NULL"
Created on 2018-06-14 by the reprex package (v0.2.0).
I guess you could try this, though I find the logic a little hard to follow on a quick read so there might be maintainability issues:
library(tidyverse)
x <- NULL
test_function <- function(x) {
dplyr::case_when(
is.null(x) ~ "I'm NULL",
sum(grepl("word", x, ignore.case = TRUE)) > 0 ~ "I'm a word",
TRUE ~ "other"
)
}
test_function(NULL)
#> [1] "I'm NULL"
test_function(NA)
#> [1] "other"
test_function(character(0))
#> [1] "other"
test_function("foobarbuzz")
#> [1] "other"
test_function("foobarwordbuzz")
#> [1] "I'm a word"
Created on 2018-06-14 by the reprex package (v0.2.0).