This function helps you replace NA values with a single provided value.
This can be classed as a kind of imputation, and is powered by
impute_fixed()
. However, we would generally recommend to impute using
other model based approaches. See the simputation
package, for example
simputation::impute_lm()
. See tidyr::replace_na()
for a slightly
different approach, dplyr::coalesce()
for replacing NAs with values from
other vectors, and dplyr::na_if()
to replace specified values with NA.
Examples
library(naniar)
x <- c(1:5, NA, NA, NA)
x
#> [1] 1 2 3 4 5 NA NA NA
replace_na_with(x, 0L)
#> [1] 1 2 3 4 5 0 0 0
replace_na_with(x, "unknown")
#> [1] "1" "2" "3" "4" "5" "unknown" "unknown"
#> [8] "unknown"
library(dplyr)
dat <- tibble(
ones = c(NA,1,1),
twos = c(NA,NA, 2),
threes = c(NA, NA, NA)
)
dat
#> # A tibble: 3 × 3
#> ones twos threes
#> <dbl> <dbl> <lgl>
#> 1 NA NA NA
#> 2 1 NA NA
#> 3 1 2 NA
dat %>%
mutate(
ones = replace_na_with(ones, 0),
twos = replace_na_with(twos, -99),
threes = replace_na_with(threes, "unknowns")
)
#> # A tibble: 3 × 3
#> ones twos threes
#> <dbl> <dbl> <chr>
#> 1 0 -99 unknowns
#> 2 1 -99 unknowns
#> 3 1 2 unknowns
dat %>%
mutate(
across(
everything(),
\(x) replace_na_with(x, -99)
)
)
#> # A tibble: 3 × 3
#> ones twos threes
#> <dbl> <dbl> <dbl>
#> 1 -99 -99 -99
#> 2 1 -99 -99
#> 3 1 2 -99