I am trying to manipulate a vector with the case_when function from dplyr. If I use the grepl function to test for certain text and change the output based on this, it works. If I use grep function it does not work.
I would like to understand why this is.
Code:
library(dplyr)
x <- 1:50
v <- case_when(
x %% 35 == 0 ~ "fizz buzz",
x %% 5 == 0 ~ "fizz",
x %% 7 == 0 ~ "buzz",
TRUE ~ as.character(x)
)
# This code works as expected
case_when(
grepl("fizz", v) ~ "FFF",
grepl("buzz", v) ~ "BZZ",
TRUE ~ v
)
# This code gives an error:
# Error: `grep("buzz", v) == 1 ~ "BZZ"`, `TRUE ~ v` must
# be length 10 or one, not 7, 50
case_when(
grep("fizz", v) == 1 ~ "FFF",
grep("buzz", v) == 1 ~ "BZZ",
TRUE ~ v
)