r - 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.
解决方案
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
推荐阅读
- mongodb - 如何在 go mongo 驱动器中使用带有 find 选项的聚合选项
- java - Spring Transaction Aware 缓存不起作用
- javascript - 如何动态使用jQuery切换方法?
- mpesa - 传递的授权类型无效 - STK 请求
- neural-network - 目前将自定义字典添加到使用转换器架构的神经机器翻译器的最佳方法是什么?
- ajax - 从 AJAX 函数中为另一个外部函数检索数据
- maven - pom.xml 中列出的 Maven 依赖项,但无法识别包 com.espertech.esperio 中的方法
- php - 警告:mysqli_connect(): (HY000/2002): 连接被拒绝
- javascript - 使地图中的功能无点
- c# - 在引用的序列化 ScriptableObject 中订阅 c# 事件时,如何避免 Unity 中的内存泄漏?