r - 重新编码多个多变量变量
问题描述
这个问题是关于在大型数据集中重新编码多变量变量。由于数据很大并且要对许多变量进行重新编码,我正在寻找一种更灵活的方法来调用所有相关变量并执行重新编码。关于重新编码有许多已解决的问题(例如,在 R 中重新编码多个变量),但这些不适合这个问题的细节。以下是数据示例:
df<-data.frame("id"=c(1:5),
"ax1"=c(2,1,4,3,4),
"ax2"=c(7,3,6,2,2),
"bx1"=c(3,5,7,1,2),
"bx2"=c(1,3,1,5,2),
"cx1"=c(1,1,7,1,6),
"cx2"=c(3,9,5,5,4))
例如,我想重新编码ax1
,bx1
和cx1
. 在这些变量上,我想分别将 1、2、3、4 重新编码为 0、1、1、0,NA
否则重新编码。使用“dplyr”包我试过
df <- df %>%
mutate_at( vars(ends_with("x1")),
list(~ ifelse( . == 1, 0, ifelse(.== 2, 1, ifelse(.==3, 1, ifelse(.==4, 0,NA))))))
但是,这不会产生预期的输出。预期的输出看起来像
id ax1 ax2 bx1 bx2 cx1 cx2
1 1 1 7 1 1 0 3
2 2 0 3 NA 3 0 9
3 3 0 6 NA 1 NA 5
4 4 1 2 0 5 0 5
5 5 0 2 1 2 NA 4
解决方案
在dplyr
中,有一个recode
专门用于此的功能
library(dplyr)
df %>%
mutate_at(vars(ends_with("x1")),
~recode(., `1` = 0, `2` = 1, `3` = 1, `4` = 0, .default = NA_real_)))
# id ax1 ax2 bx1 bx2 cx1 cx2
#1 1 1 7 1 1 0 3
#2 2 0 3 NA 3 0 9
#3 3 0 6 NA 1 NA 5
#4 4 1 2 0 5 0 5
#5 5 0 2 1 2 NA 4
推荐阅读
- python - 如何在 python 中读取 find() 查询返回的游标对象?
- hadoop - 使用或验证两个密钥表(Hadoop 和 Kafka kerberos)运行火花流作业
- php - 在 PHP 中使用 Stripe webhook 时出现“无法从标头中提取时间戳和签名”错误
- ios - 有没有办法自动化仪器的功能?
- pandas - Pandas 将具有“0%”的列转换为对象而不是读取为浮点数
- python - 无法导入同一文件中的模块
- php - 即使最终结果仍然是选择,也无法从其中包含插入或选择查询以外的存储过程中检索数据
- java - 大摇大摆是否保存任何文件
- react-native - 如何使用 react-navigation 从顶级应用页面导航到页面?
- javascript - 是否可以在 MSBOT 卡中呈现 javascript 脚本?