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?