Hi,
Suppose I have the following tibble:
library(tidyverse)
tiny <-
tibble(a = 1, b = factor(1, levels = 1:2)) %>%
add_row(a = 2, b = NA)
tiny
#> # A tibble: 2 x 2
#> a b
#> <dbl> <fct>
#> 1 1 1
#> 2 2 <NA>
and I want to replace the NA
value in column b
by 2.
First approach:
tiny %>%
mutate(b = case_when(is.na(b) ~ 2, TRUE ~ b))
#> Error: must be a double vector, not a `factor` object
Second approach:
tiny %>%
mutate(
b =
case_when(
is.na(b) ~ factor(2, levels = levels(b)),
TRUE ~ b
)
)
#> # A tibble: 2 x 2
#> a b
#> <dbl> <fct>
#> 1 1 1
#> 2 2 2
Created on 2020-07-04 by the reprex package (v0.3.0)
Is there a less verbose alternative to the second approach that resembles the first?