Use mutate() to return a logical vector - R for Data Science

I think your last if_else is missing the FALSE that should be returned if none of the previous conditions were TRUE. A simplified example is below. I think the %in% solution is preferable but use whatever works for you.

DF <- data.frame(rincome = c("A", "B", "C", "D", "E", "A", "Z"))
library(dplyr)

DF <- DF %>% mutate(income_na = if_else(rincome == "A", TRUE,
                                        if_else(rincome == "B", TRUE,
                                        if_else(rincome == "C", TRUE, 
                                        FALSE))))
DF
#>   rincome income_na
#> 1       A      TRUE
#> 2       B      TRUE
#> 3       C      TRUE
#> 4       D     FALSE
#> 5       E     FALSE
#> 6       A      TRUE
#> 7       Z     FALSE

Created on 2020-02-09 by the reprex package (v0.2.1)

1 Like