Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the %in% operator on multiple columns

Tags:

r

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.

like image 943
Jon Avatar asked Mar 02 '23 08:03

Jon


1 Answers

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
like image 89
AndS. Avatar answered Mar 08 '23 04:03

AndS.