'How can I coalesce two columns with alternating missing values (Yes/No survey data)? [duplicate]
I am trying to merge two columns in my dataset based on binary survey responses (Yes/No). The dataset looks like this: Treatment1: "No", N/A, N/A, "Yes", "No", N/A, "No" ... Treatment2: N/A, "Yes", "No", N/A, N/A, "No", N/A ...
The scores are thus corresponding to each other based on the treatment group of each respondent. Now, I am trying to create a new variable that merges these values into one single variable: "No", "Yes", "No" ... so that the N/A's are substituted by the answers from the other Treatment.
I tried using coalesce() but the resulting variable only has the values from Treatment1, it somehow doesn't merge them. I can't find the reason why! Perhaps someone can help - I am new to R!
Thanks!
Solution 1:[1]
There are probably more elegant solutions, but try using ifelse():
df <- data.frame(t1 = c("yes", "no", NA, "yes"),
t2 = c(NA, NA, "no", NA))
df$t_final <- ifelse(!is.na(df$t1), df$t1, df$t2)
# t1 t2 t_final
#1 yes <NA> yes
#2 no <NA> no
#3 <NA> no no
#4 yes <NA> yes
If you want to use coalesce():
df$t_final.dplyr <- dplyr::coalesce(df$t1, df$t2)
# t1 t2 t_final.dplyr
#1 yes <NA> yes
#2 no <NA> no
#3 <NA> no no
#4 yes <NA> yes
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
