I feel like there should be an efficient way to mutate new columns with dplyr
using case_when
and contains
, but cannot get it to work.
I understand using case_when
within mutate
is "somewhat experimental" (as in this post), but would be grateful for any suggestions.
Doesn't work:
library(tidyverse)
set.seed(1234)
x <- c("Black", "Blue", "Green", "Red")
df <- data.frame(a = 1:20,
b = sample(x,20, replace=TRUE))
df <- df %>%
mutate(group = case_when(.$b(contains("Bl")) ~ "Group1",
case_when(.$b(contains("re", ignore.case=TRUE)) ~ "Group2")
)
contains
is only to be used insideselect
. At least, that's what I gather from the documentation of?contains
. – Rich Scrivenmutate
too, although thegrep
solution below is a good alternative. – Peter MacPherson