I have a set, W <- c("a","b","c")
And a dataframe
df <- data.frame(col1 = c(1,2,3), col2 = c("a","b","c"), col3 =c("t","b","p"))
I want to run the %in%
operator on multiple columns to return TRUE/FALSE
for columns 2 and 3. I want column 1 to remain the same.
I know I can do
>df$col1 <- df$col1 %in% W
and
>df$col2 <- df$col2 %in% W
I'm unsure how I can do this in one line. I am also fairly new to R and programming in general.
You could apply a function across both of the columns:
library(tidyverse)
W <- c("a","b","c")
df <- tibble(col1 = c(1,2,3), col2 = c("a","b","c"), col3 =c("t","b","p"))
df |>
mutate(across(c(col2, col3), \(x) x %in% W))
#> # A tibble: 3 x 3
#> col1 col2 col3
#> <dbl> <lgl> <lgl>
#> 1 1 TRUE FALSE
#> 2 2 TRUE TRUE
#> 3 3 TRUE FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With