vendredi 26 juillet 2019

How do I grab the first non-NA column matching a string if a certain column is NA

I haven't seen a similar question for this issue (it's pretty specific).

I have three people who can be chosen to give answers to questions about a patient. Only two of those three people are actually used for any particular patient (in my real data it's always two who are chosen, but among a pool of 10 people).

If the initial two people disagree, a third person is used (3rdOpinion) and that opinion overrides the others.

Therefore, the final result = the 3rd opinion result, UNLESS the initial two opinions are the same (i.e. 3rdOpinion is NA), in which case the final result is just the opinion given by the initial two people (i.e. the first non-NA value for that question for that patient)

So for example patient 1 question 1, Ben and Chris disagreed, so 3rdOpinion was used as the final result.

For question 2, patient 2, Adam and Chris both said "yes", so the final result is "yes" and the 3rd opinion wasn't used.

How can I code my data to give the last two columns, Question1_final and Question2_final?

#Code to reproduce the data with the desired last two columns:
Patient <- c("1","2","3")
Question1_Adam <- c(NA,"Yes","No")
Question2_Adam <- c(NA,"Yes","No")
Question1_Ben <- c("Yes",NA,"Unlikely")
Question2_Ben <- c("No",NA,"No")
Question1_Chris <- c("Probably","Probably",NA)
Question2_Chris <- c("Unlikely","Yes",NA)
Question1_3rdOpinion <- c("Probably","Yes","No")
Question2_3rdOpinion <- c("No",NA,NA)
Question1_final <- c("Probably","Yes","No")
Question2_final <- c("No","Yes","Unlikely")
df <- data.frame(Patient, Question1_Adam, Question2_Adam, Question1_Ben, Question2_Ben, Question1_Chris, Question2_Chris, Question1_3rdOpinion, Question2_3rdOpinion, Question1_final, Question2_final)

I figured I needed something like this, but not sure how to code the last part:

df <- transform(df, Q1_final = ifelse(!is.na(Question1_3rdOpinion), Question1_3rdOpinion, *here I would somehow grep the first non-NA question 1 value*))

Aucun commentaire:

Enregistrer un commentaire