Home > OS >  How can I change multiple rows to NA for a "check all that apply" question?
How can I change multiple rows to NA for a "check all that apply" question?

Time:01-12

I have a question in my survey that is check all. It asks: What animals did you own growing up? (check all that apply)

  • Cat
  • Dog
  • Rabbit
  • Guinea pig
  • Mouse
  • None

The survey was collected in RedCap, so each time a question was checked, it was labeled at "Yes" and if it was left unchecked it was labeled as "no". Each answer (dog, cat, etc) is a different column in my dataset (column_cat, column_dog).

The problem that I have is that not everyone answered this question. Some people skipped it by accident. This means that these skipped questions in R are labeled at "No" when in actuality they should be NA because none of the six possible answers have been checked.

Is there any easy way to quickly recode all this missing data as NA for each variable? I have several variables like this, so I am hoping there is a quick(ish) solution

I think I might possibly be able to use the function replace_with_na_if() but I am not sure what is the most efficient approach.

CodePudding user response:

Using base R

df1[!rowSums(df1 == "Yes", na.rm = TRUE ),] <- NA

CodePudding user response:

With this example data:

dat <- data.frame(
  column_cat = c("Yes", "No", "No"),
  column_dog = c("Yes", "No", "No"),
  column_none = c("No", "Yes", "No")
)

dat
#   column_cat column_dog column_none
# 1        Yes        Yes          No
# 2         No         No         Yes
# 3         No         No          No

You can use dplyr::if_all() to test across multiple columns, and dplyr::across() to modify them:

library(dplyr)

dat %>%
  mutate(across(
    column_cat:column_none,
    \(x1) ifelse(
      if_all(column_cat:column_none, \(x2) x2 == "No"), 
      NA, 
      x1
    )
  ))
#   column_cat column_dog column_none
# 1        Yes        Yes          No
# 2         No         No         Yes
# 3       <NA>       <NA>        <NA>
  •  Tags:  
  • r
  • Related