Search code examples
rdplyrnarecode

dplyr - how to recode to NA?


I'm trying the following:

data %>%
   mutate_at(vars(Q1), recode, "I don't agree" = 0, "I agree" = 1, "I don't know" = NA)

But I'm getting the following error:

Q1 must be a double vector, not a logical vector

How can I proprely recode "I don't know" to missing values using dplyr?


Solution

  • Using the iris dataset, this code works

    library(dplyr)
    iris %>% 
      mutate_at(vars(Species), recode, setosa = 0, versicolor = 1, virginica = NA_real_)
    

    Basically you need to use NA_real_ instead of the simple NA