I have the following data frame:
df <- structure(list(x = c("cc", "aa", "BB", "dd"), y = c("ee", "dd",
"ff", "gg"), z = c("AA", "gg", "bb", "dd")), row.names = c(NA,
-4L), class = c("tbl_df", "tbl", "data.frame"))
I would like to create a binary column indicating whether each row contains "aa" (case insensitive) in any column. So in this case the first two values will be TRUE, and the last true will be FALSE. How can I do this using dplyr? all the answers explain how to filter those rows, rather than how to book-keep them
We could use a vectorized option with if_any
library(dplyr)
library(stringr)
df %>%
mutate(xyz = +(if_any(everything(),
~ str_detect(., regex('aa', ignore_case = TRUE)))))
-output
# A tibble: 4 x 4
x y z xyz
<chr> <chr> <chr> <int>
1 cc ee AA 1
2 aa dd gg 1
3 BB ff bb 0
4 dd gg dd 0
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments