Impute the mode value into a vector with missing values
Usage
impute_mode(x)
# S3 method for default
impute_mode(x)
# S3 method for integer
impute_mode(x)
# S3 method for factor
impute_mode(x)
Arguments
- x
vector
This approach adapts examples provided from stack overflow, and for the integer case, just rounds the value. While this can be useful if you are imputing specific values, however we would generally recommend to impute using other model based approaches. See the
simputation
package, for examplesimputation::impute_lm()
.
Examples
vec <- rnorm(10)
vec[sample(1:10, 3)] <- NA
impute_mode(vec)
#> [1] 1.371914294 0.413380638 -1.669939609 0.069016915 0.069016915
#> [6] -1.158660464 0.001326548 -1.771324596 0.018509032 0.069016915
library(dplyr)
dat <- tibble(
num = rnorm(10),
int = rpois(10, 5),
fct = factor(LETTERS[1:10])
) %>%
mutate(
across(
everything(),
\(x) set_prop_miss(x, prop = 0.25)
)
)
dat
#> # A tibble: 10 × 3
#> num int fct
#> <dbl> <int> <fct>
#> 1 -0.100 6 A
#> 2 -0.342 4 B
#> 3 -0.108 NA C
#> 4 1.51 6 D
#> 5 0.202 10 NA
#> 6 2.26 3 F
#> 7 NA NA NA
#> 8 -1.30 8 H
#> 9 NA 6 I
#> 10 -0.0709 3 J
dat %>%
nabular() %>%
mutate(
num = impute_mode(num),
int = impute_mode(int),
fct = impute_mode(fct)
)
#> # A tibble: 10 × 6
#> num int fct num_NA int_NA fct_NA
#> <dbl> <dbl> <fct> <fct> <fct> <fct>
#> 1 -0.100 6 A !NA !NA !NA
#> 2 -0.342 4 B !NA !NA !NA
#> 3 -0.108 6 C !NA NA !NA
#> 4 1.51 6 D !NA !NA !NA
#> 5 0.202 10 B !NA !NA NA
#> 6 2.26 3 F !NA !NA !NA
#> 7 -0.0964 6 B NA NA NA
#> 8 -1.30 8 H !NA !NA !NA
#> 9 -0.0964 6 I NA !NA !NA
#> 10 -0.0709 3 J !NA !NA !NA