首页 > 解决方案 > R - 如何重新编码多列

问题描述

我正在尝试跨多个列将 6s 更改为 NAs。我曾尝试使用 mutate_at 命令dplyr,但似乎无法使其工作。有任何想法吗?

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.

标签: rdplyrrecode

解决方案


dplyr具有执行na_if()此任务的功能。您的代码几乎就在那里,可以使用:

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

推荐阅读