Use of any_of() within case_when()

I'm trying to create a new variable using mutate() based on conditions occurring in other variables (that may or may not exist). I would love to use any_of() but that only works with a select()
Basically I would lover to implement something like this:

mtcars %>% 
  mutate(., speed = case_when(
    any_of(c("columns", "that", "maynot", "exist", "cyl", "gear") == 4) ~ "fast",
         TRUE ~ "slow")

My initial code looked like this:

mtcars %>% 
  mutate(speed = case_when(
    columns == 4 | that == 4 | maynot == 4 | exist == 4 | cyl == 4 | gear == 4 ~ "fast",
    TRUE ~ "slow")

But both don't work if a variable doesn't exist. The reason I want to do this is that I want to loop it over several dataframes/files. Some of them will have all of those variables (columns, that, maynot, exist, cyl, gear). Some will only have "cyl" and "gear" and some other may have another selection of the full list. Mutate does not work if the variables/columns you mention don't exist. Anyone has an idea how I would be able to implement this?

how about this?


df <- iris %>% 

iris %>%

Thanks, that did help. For anyone finding this post in the future, the following code was actually the correct answer and worked for my case:


df <- mtcars %>% 
  select(any_of(c("columns", "that", "maynot", "exist", "cyl", "gear"))

mtcars %>%
  mutate(speed=ifelse(rowSums(df==4, na.rm = TRUE)>0, "fast", "slow"))

I'm glad you worked it out.
I wanted to write it all in one line, or pipe it together,
but the people who design the tidyverse might say that forcing the code to be complicated is a bad attempt, so I decided to split the code.

I hope you continue to enjoy R.


1 Like

Here is a very explicit method, which might be useful for debugging

mtcars %>% mutate(
  across(any_of(c("columns", "that", "maynot", "exist", "cyl", "gear")),
        ~.  ==4,.names = "lgl_test_{col}"),

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.