Mutate based on a condition

56 views Asked by At

I am trying to use mutate + ifelse to create a new variable in the dataset. My example dataset is below

df = structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), resp_gender = c("female", 
"male", "female", "female", "male", "female", "male", "male", 
"female", "female"), hoh_gender = c("male", "male", "male", "male", 
"female", "male", "female", "female", "male", "male"), is_hoh = c("no", 
"no", "no", "yes", "no", "no", "yes", "no", "no", "yes"), gender_final = c("male", 
"male", "male", "female", "female", "male", "male", "female", 
"male", "female")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-10L))

The goal is to create the column gender_final so that if is_hoh == yes then it takes the value of hoh_gender and if it's no it takes the value of resp_gender. I am using the code below which seems not to be producing accurate results

mutate(gender_final  = ifelse(is_hoh == "yes", hoh_gender, resp_gender))
1

There are 1 answers

1
GRowInG On BEST ANSWER

Not sure how you connect your mutate line to your dataset, given that it already has a column called gender_final but it seems to work just like you expected. In my suggestion, I have just called the new column gender_final2 because I didn't want to change your original data.

library(dplyr)

# Use df and conditional mutate to create gender_final2
df <- df %>%
  mutate(gender_final2  = ifelse(is_hoh == "yes", hoh_gender, resp_gender))

df

    id resp_gender hoh_gender is_hoh gender_final gender_final2
   <dbl> <chr>       <chr>      <chr>  <chr>        <chr>        
 1     1 female      male       no     male         female       
 2     2 male        male       no     male         male         
 3     3 female      male       no     male         female       
 4     4 female      male       yes    female       male         
 5     5 male        female     no     female       male         
 6     6 female      male       no     male         female       
 7     7 male        female     yes    male         female       
 8     8 male        female     no     female       male         
 9     9 female      male       no     male         female       
10    10 female      male       yes    female       male