【发布时间】:2018-11-28 20:21:43
【问题描述】:
我有一个大型数据集,需要将一些数值变量重新编码为其他数值。我的数据集的一部分如下所示:
condition.10 financial.condition behavior.condition outcome Gender Race
1 6 1 3 0 Male 5
2 7 0 4 0 Female 5
3 5 0 3 1 Female 5
4 2 1 1 1 Male 2,5
5 10 1 5 0 Female 5
6 6 1 3 1 Male 5
我想将种族重新编码为 1、2、3 的 3 个“箱”,分别为“白色”、“黑色”和“其他”。我已经设法用这段代码实现了这一点:
mydata$Race <- NA
mydata$Race <- mydata$Q73
mydata$Race[mydata$Race==1|mydata$Race==2|mydata$Race==4|mydata$Race==6]<-6
mydata$Race[mydata$Race==3]<-2
mydata$Race[mydata$Race==5]<-1
mydata$Race[mydata$Race==6]<-3
我也试过这个:
case_when(mydata$Race %in% c(1,2,4,6) ~3,
mydata$Race %in% 3 ~ 2,
mydata$Race %in% 5 ~1,
TRUE ~ as.numeric(mydata$Race))
第一位给了我我需要的东西,但它没有考虑到人们检查两场比赛,比如第四排的比赛。
任何建议将不胜感激。我已经准备好从 car package 和 dplyr 重新编码。
也许只是我太新了,但不能做基础知识会很痛苦。
unique(mydata$Race)
# [1] 5 2,5 2 3 6 3,5 1,5 1,2,4,5 1 1,2,5 4,6 3,6 2,3 1,3 4
# [16] 2,4,5,6 1,3,5 4,5
# Levels: 1 1,2,4,5 1,2,5 1,3 1,3,5 1,5 2 2,3 2,4,5,6 2,5 3 3,5 3,6 4 4,5 4,6 5 6
注意:我是非常 R 的新手,正在寻求一些指导。
【问题讨论】:
-
如何将第 4 行
2, 5编码为 1 或 3? -
稍后再决定。理想情况下,我希望 2 更改为 3,而 5 更改为 1。如果我被按下,我会说 1。
-
你能检查一下 Race 列中的唯一值,给我们看看
unique(mydata$Race)的输出吗? -
unique(mydata$Race) [1] 5 2,5 2 3 6 3,5 1,5 1,2,4,5 1 1,2,5 4,6 3,6 2,3 1,3 4 [16] 2,4,5,6 1,3,5 4,5 Levels: 1 1,2,4,5 1,2,5 1,3 1,3,5 1,5 2 2,3 2,4,5,6 2,5 3 3,5 3,6 4 4,5 4,6 5 6我不知道如何使它更具可读性 -
我在您的帖子中添加了 unique 的输出,您随时可以通过单击“编辑”为您的帖子添加更多详细信息。