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))
Not sure how you connect your
mutateline to your dataset, given that it already has a column calledgender_finalbut it seems to work just like you expected. In my suggestion, I have just called the new columngender_final2because I didn't want to change your original data.