Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the R case_when function work with the grepl function but not with grep function [duplicate]

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
)
like image 402
Joon Avatar asked May 29 '26 05:05

Joon


1 Answers

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
)
like image 198
Thomas Wire Avatar answered Jun 01 '26 00:06

Thomas Wire