I'm trying to create a conditional variable using mutate in dplyr which doesn't appear to be working for me. Please see example dataframe and combined score variable I attempt to create. Notice that the 3rd observation of the new variable 'combined.score' is not the sum of B, C and D. It appears that only the first observation is calculated and this value is used for each row observation.
What am I missing here? Would like a reason for why this is happening (not so much alternative code or a solution)
df <-
data.frame(B=c(1,0,0),
C=c(3,4,9),
D=c(1,1,0))
#A function to calculate stations whether there is a communication or process component or both
df <- df %>%
mutate(combined.score = ifelse("B" %in% names(.) & "C" %in% names(.) & "D" %in% names(.), B + C + D,
ifelse("B" %in% names(.) & "C" %in% names(.), B + C,
B))) %>%
mutate(combined.score.correct = B + C + D)
"B" %in% names(.) & "C" %in% names(.) & "D" %in% names(.)is eitherTRUEorFALSE;ifelseis best used for cases of vectors of logical values; what exactly are you trying to test for with this statement? - MichaelChiricorowSums(df)gives you exactly what you want ascombined.score. - MichaelChirico