na_when: Set variable to NA based on conditions

na_whenR Documentation

Set variable to NA based on conditions

Description

This function sets a variable to NA based on one or several logical conditions. It would most naturally be used inside a dplyr-mutate call. By default, the conditions are combined with a logical OR, yet this can be changed to AND by setting operator = "&".

Usage

na_when(x, ..., operator = "|")

Arguments

x

The variable to transform.

...

One or more logical conditions, involving x or other variables.

operator

Name of a logical operator to combine the conditions. Defaults to "|" (or), "&" (and) is the other common choice, though "xor" would also work.

Details

Note that the function is called na_when to prevent clashing with dplyr's na_if ... even though the latter might be the more intuitive name.

Examples

library(dplyr)

ess_health %>% 
    mutate(eisced = na_when(eisced, cntry == "DE", agea < 21))
    
mtcars %>% 
    mutate(carb = na_when(carb, cyl > 6, mpg < 19, operator = "&"))     

LukasWallrich/timesaveR documentation built on Nov. 29, 2024, 4:47 a.m.