add new column based on two other columns with several conditions, character
I like case_when
from dplyr
for these types of complex conditionals.
df<-tibble::tribble(
~job, ~honorary,
"yes", "yes",
"yes", "no",
"no", "yes",
"yes", "yes",
"yes", NA,
NA, "no"
)
library(dplyr)
df_new <- df %>%
mutate(result=case_when(
job=="yes" & honorary=="yes" ~ "both",
honorary=="yes" ~ "honorary",
job=="yes" ~ "job",
is.na(honorary) & is.na(job) ~ NA_character_,
is.na(honorary) & job=="no" ~ NA_character_,
is.na(job) & honorary=="no" ~ NA_character_,
TRUE ~ "other"
))
df_new
#> # A tibble: 6 × 3
#> job honorary result
#> <chr> <chr> <chr>
#> 1 yes yes both
#> 2 yes no job
#> 3 no yes honorary
#> 4 yes yes both
#> 5 yes <NA> job
#> 6 <NA> no <NA>
or in base R
df_new<-df
df_new=within(df_new,{
result=NA
result[ honorary=="yes"] = "honorary"
result[ job=="yes"] = "job"
result[job=="yes" & honorary=="yes"]='both'
})
Created on 2022-01-16 by the reprex package (v2.0.1)