I would like to use a combination of mutate, across, and case_when to set some cases to NA (missing) across multiple variables.
Say I have an indicator variable "vs" flagging cases that should be NA for variables "carb" and "gear". I would like to use something like this to set those cases to missing on both those variables at once:
data(mtcars) #load mtcars data
mtcars$carb <- as.integer(mtcars$carb) #set to integer,
#for purposes of illustration
mtcars <- mtcars %>%
mutate(across(c(gear:carb), ~ case_when(vs==1~NA,
T~.)))
I would like this to change "gear" and "carb" to NA for all cases for which "vs" is equal to 1. However, since carb is an integer and gear is numeric, I run into a type conflict:
Error: Problem with `mutate()` input `..1`.
ℹ `..1 = across(c(gear:carb), ~case_when(vs == 1 ~ NA, T ~ .))`.
x must be a logical vector, not a double vector.
If I were using mutate on each variable individually, I would replace NA with NA_integer_ for 'carb' and NA with NA_real_ for 'gear'. I can't do that here, since the variables contain different types of data.
Is there any way around this, or can I only use mutate(across()) like this with variables of the same type?
Thank you!