I am working with survey data where I need to identify whether responses were not applicable or simply skipped.
x1andx2are my primary response questions. x3 is only filled out when someone indicates ifx1andx2are not applicable.- I want row 1 and row 2 to equal 0 as
x1andx2were not applicable, and I want row 4 to equal 1 asx1andx2was correctly reported as "None of the above." - Row 3 is the truly missing observation as neither
x1,x2, orx3were answered.
My code below works, but is there a simplier way where I can just refer to my list variable rather than writing a lengthy AND statement using x1 and x2? I have simplified this example as my full dataset has 10+ x variables.
library(dplyr)
df3 <- tibble(x1 = c("Yes", "No", NA, NA), x2 = c("Yes", "Yes", NA, NA), x3 = c(NA, NA, NA, "None of the above"))
list <- c("x1", "x2")
df3 %>%
mutate(
x3 = coalesce(as.integer(x3 == "None of the above"), 0),
x3 = case_when(
x3 == 1 ~ 1,
is.na(x1) & is.na(x2) ~ NA_real_,
TRUE ~ 0))