set_na_if() is a scoped variant of set_na, where values will be replaced only with NA's for those variables that match the logical condition of predicate.

set_na_if(x, predicate, na, drop.levels = TRUE, as.tag = FALSE)



A vector or data frame.


A predicate function to be applied to the columns. The variables for which predicate returns TRUE are selected.


Numeric vector with values that should be replaced with NA values, or a character vector if values of factors or character vectors should be replaced. For labelled vectors, may also be the name of a value label. In this case, the associated values for the value labels in each vector will be replaced with NA. na can also be a named vector. If as.tag = FALSE, values will be replaced only in those variables that are indicated by the value names (see 'Examples').


Logical, if TRUE, factor levels of values that have been replaced with NA are dropped. See 'Examples'.


Logical, if TRUE, values in x will be replaced by tagged_na, else by usual NA values. Use a named vector to assign the value label to the tagged NA value (see 'Examples').


x, with all values in na being replaced by NA. If x is a data frame, the complete data frame x will be returned, with NA's set for variables specified in ...; if ... is not specified, applies to all variables in the data frame.

See also

replace_na to replace NA's with specific values, rec for general recoding of variables and recode_to for re-shifting value ranges. See get_na to get values of missing values in labelled vectors.


dummy <- data.frame(var1 = sample(1:8, 100, replace = TRUE),
                    var2 = sample(1:10, 100, replace = TRUE),
                    var3 = sample(1:6, 100, replace = TRUE))

p <- function(x) max(x, na.rm = TRUE) > 7
tmp <- set_na_if(dummy, predicate = p, na = 8:9)
#>   var1 var2 var3
#> 1    6    7    4
#> 2    2    6    5
#> 3    2   NA    4
#> 4    1    4    1
#> 5    3    6    3
#> 6    7    1    5