Search code examples
rdplyrrecode

R - How to recode multiple columns


I am trying to change the 6s to NAs across multiple columns. I have tried using the mutate_at command in dplyr, but can't seem to make it work. Any ideas?

library(dplyr)
ID <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) #Create vector of IDs for ID column.
Score1 <- c(1, 2, 3, 2, 5, 6, 6, 2, 5, 4) #Create vector of scores for Score1 column.
Score2 <- c(2, 2, 3, 6, 5, 6, 6, 2, 3, 4) #Create vector of scores for Score2 column.
Score3 <- c(3, 2, 3, 4, 5, 5, 6, 2, 6, 4) #Create vector of scores for Score3 column.
df <- data.frame(ID, Score1, Score2, Score3) #Combine columns into a data frame.
VectorOfNames <- as.vector(c("Score1", "Score2", "Score3")) #Create a vector of column names.
df <- mutate_at(df, VectorOfNames, 6=NA) #Within the data frame, apply the function (6=NA) to the columns specified in VectorOfNames.

Solution

  • dplyr has the na_if() function for precisely this task. You were almost there with your code and can use:

    mutate_at(df, VectorOfNames, ~na_if(.x, 6))
    
       ID Score1 Score2 Score3
    1   1      1      2      3
    2   2      2      2      2
    3   3      3      3      3
    4   4      2     NA      4
    5   5      5      5      5
    6   6     NA     NA      5
    7   7     NA     NA     NA
    8   8      2      2      2
    9   9      5      3     NA
    10 10      4      4      4