I have a tibble, df
, with a factor, A
, I wish to:
1) copy of,C
, and
2) recode based on a second variable, B
.
At the moment I'm doing it in this roundabout way. I'm quite confused by the conditional recoding of factor. I also looked at dplyr
's recode
, but couldn't work out a smarter method.
library(tibble)
df <- tibble(
A = factor(c(NA, "b", "c")),
B = c(1,NA,3)
)
My initial tibble
df
#> # A tibble: 3 x 2
#> A B
#> <fctr> <dbl>
#> 1 <NA> 1
#> 2 b NA
#> 3 c 3
Step #1 in my current solution
df$C <- with(df, ifelse(is.na(B), 'B is NA', A))
df
#> # A tibble: 3 x 3
#> A B C
#> <fctr> <dbl> <chr>
#> 1 <NA> 1 <NA>
#> 2 b NA B is NA
#> 3 c 3 2
Step #2 in my current solution
df$C <- dplyr::recode_factor(df$C, '2' = 'c')
df
#> # A tibble: 3 x 3
#> A B C
#> <fctr> <dbl> <fctr>
#> 1 <NA> 1 <NA>
#> 2 b NA B is NA
#> 3 c 3 c
How am I suppose to do this?
Using dplyr::if_else
, convert factor to character, then convert to factor again:
library(dplyr)
df %>%
mutate(C = factor(if_else(is.na(B), "B is NA", as.character(A))))
# # A tibble: 3 x 3
# A B C
# <fctr> <dbl> <fctr>
# 1 <NA> 1 <NA>
# 2 b NA B is NA
# 3 c 3 c