if_na: Replace Missing Values

Description Usage Arguments Examples

View source: R/if_na.R

Description

Replaces missing values with the given value, or optionally conditions the replacement on the expressions given in ..., which are applied to the inputs in the same way as filter.

Usage

1
if_na(.x, ..., then = default_value(.x), otherwise = NULL)

Arguments

.x

Input vector of values

...

Additional expressions to condition replacement. NA values are only replaced when the additional expression matches.

then

Replacement value. Defaults to a value based on the input type and favors 0, FALSE, "" or empty lists according to the input type.

otherwise

If given, provides a secondary replacement value to be subsituted for missing values when the conditions in ... are FALSE.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
library(dplyr)
storms <- storms %>%
  filter(name == "Erika", year == 2003) %>%
  select(name, year, status, wind, contains("diameter"))

# Default is replacement with appropriate default (0, FALSE, "", etc.)
storms %>%
  mutate(hu_diameter = if_na(hu_diameter))

# Replacement can be single value or vector of values
storms %>%
  mutate(
    ts_diameter = if_na(ts_diameter, then = 30),
    hu_diameter = if_na(hu_diameter, then = rnorm(11, 100))
  )

# Replacement can be predicated on other conditions in addition to missingness
storms %>%
  mutate(
    hu_diameter = if_na(hu_diameter, then = 30, status == "hurricane")
  )

# Can provide a secondary value for missing values when the conditions
# are not met
storms %>%
  mutate(
    ts_diameter = if_na(ts_diameter, then = wind, status == "tropical storm", otherwise = 0)
  )

GerkeLab/grkmisc documentation built on Feb. 23, 2020, 6:50 a.m.