0

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!

  • 1
    https://stackoverflow.com/help/minimal-reproducible-example Please read and share your data and code you were using. Otherwise it‘s impossible to help ypu. – deschen Feb 24 '22 at 13:18

1 Answers1

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

jpsmith
  • 11,023
  • 5
  • 15
  • 36