简体   繁体   中英

Type conflict setting multiple variables to NA with mutate, across, case_when

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!

Another option would be to use an if statement:

library(dplyr)

mtcars$carb <- as.integer(mtcars$carb)

mtcars <- mtcars %>%
  mutate(across(c(gear:carb), ~ case_when(
    vs == 1 ~ if (is.integer(.)) NA_integer_ else NA_real_,
    T ~ .
  )))

But the much more clever approach I learned thanks to the comment by @r2evans would be use .[NA] which "will always give the appropriate NA type":

mtcars <- mtcars %>%
  mutate(across(c(gear:carb), ~ case_when(
    vs == 1 ~ .[NA],
    T ~ .
  )))

head(mtcars)
#>                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1   NA   NA
#> Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0   NA   NA
#> Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0   NA   NA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM