Home > front end >  Check if single column is equal to any multiple others
Check if single column is equal to any multiple others

Time:10-07

My question seems simple, but I just can't do it. I have a dataframe with multiple columns with the name starting with coa and another column p with values like A, D, F, and so on, which changes according to the id.

All I found is how to do this matching with a fixed value, let's say "A", as below:

df <-df %>%
  mutate(ly = any(str_detect(c_across(starts_with("coa")), "A")))

However, in my case, I want to compare to the column p specifically, where p changes, something like this:

df <-df %>%
  mutate(ly = any(str_detect(c_across(starts_with("coa")), p)))

In this case, I get the error:

x no applicable method for 'type' applied to an object of class "factor"

Any thoughts? Thanks!

CodePudding user response:

If we need to create a column, use if_any

library(dplyr)
library(stringr)
df <- df %>%
      mutate(ly = if_any(starts_with("coa"), ~ str_detect(.x, p)))

CodePudding user response:

I think this is a good place to use dplyr::across. You can run vignette('colwise') for a more comprehensive guide, but the key point here is that we can mutate all columns starting with "coa" simultaneously using the function == and we can pass a second argument, p, to == using the ... option provided by across.

library(dplyr)

df <- tibble(p = 1:10, coa1 = 1:10, coa2 = 11:20)

df %>%
  mutate(across(.cols = starts_with('coa'), .fns = `==`, p))
  •  Tags:  
  • r
  • Related