3

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
)
oguz ismail
  • 1
  • 16
  • 47
  • 69
Joon
  • 2,127
  • 1
  • 22
  • 40

1 Answers1

4

If you're dead set on using grep you could do this:

case_when(
    x %in% grep("fizz", v) ~ "FFF",
    x %in% grep("buzz", v) ~ "BZZ",
    TRUE ~ v
)
Thomas Wire
  • 272
  • 1
  • 9