That's because you have gray = NULL
. When you call if(xx)
, the value of xx
can be TRUE
or FALSE
. If xx=NULL
it means it doesn't exist, and if()
doesn't know what to do with it.
So you have 2 possibilities: either set the default as FALSE
, and don't use NULL
anywhere (that's my favorite), or if you want to use NULL
, you have to test for it with is.null()
, which returns TRUE
or FALSE
.
suppressPackageStartupMessages({
library(dplyr)
library(lubridate)
})
set.seed(123)
dat <- data.frame(from_europe = sample(c(TRUE,FALSE), 6, replace = TRUE),
birthdate = c("2010-01-11","2011-01-11","2011-01-12"),
happiness = rnorm(6),
color = c("mauve","fuscia","magenta"))
cats_clean1 <- function(.data, orange = FALSE, gray = FALSE) {
if (gray) {
filtered <- .data %>% filter(from_europe)
} else if (orange) {
filtered <- .data %>% filter(birthdate >= ymd("2011-01-11"))
} else {
filtered <- .data
}
filtered %>%
group_by(color) %>%
summarize(happiness = sum(happiness, na.rm = TRUE))
}
cats_clean2 <- function(.data, orange = NULL, gray = NULL) {
if (! is.null(gray)) {
filtered <- .data %>% filter(from_europe)
} else if (! is.null(orange)) {
filtered <- .data %>% filter(birthdate >= ymd("2011-01-11"))
} else {
filtered <- .data
}
filtered %>%
group_by(color) %>%
summarize(happiness = sum(happiness, na.rm = TRUE))
}
cats_clean1(dat)
#> # A tibble: 3 × 2
#> color happiness
#> <chr> <dbl>
#> 1 fuscia -1.14
#> 2 magenta 1.03
#> 3 mauve 0.531
cats_clean2(dat)
#> # A tibble: 3 × 2
#> color happiness
#> <chr> <dbl>
#> 1 fuscia -1.14
#> 2 magenta 1.03
#> 3 mauve 0.531
Created on 2022-12-14 by the reprex package (v2.0.1)
(thanks to @technocrat for the reprex!)