将Age变量转换为序数变量

时间:2017-02-10 19:09:26

标签: r recode

我是R的新手。

如何将数值变量转换为序数变量?例如,假设我想将年龄重新编码为四个类别(< 65,66-75,75-85,85 +):

Age
55
60
65
70
75
80
85
90
95

变为

Age
Young-Old
Young-Old
Med-Old
Med-Old
Med-Old
Old
Old
Old-Old
Old-Old

2 个答案:

答案 0 :(得分:1)

您可以使用dplyr case_when

轻松完成此操作
library(dplyr)
age <- c(55, 60, 65, 70, 75, 80, 85, 90, 95)

age2 <- case_when(age <= 65 ~ 'Young-Old',
                  between(age, 66, 75) ~ 'Med-Old',
                  between(age, 76, 85) ~ 'Old',
                  age >= 86 ~ 'Old-Old'
                  )
age2 <- as.factor(age2)

答案 1 :(得分:1)

您可以使用cut命令执行此操作。

age <- c(55, 60, 65, 70, 75, 80, 85, 90, 95)
breaks <- c(0,65,75,85,Inf)
age_transformed <- cut(age,breaks = breaks)

levels(age_transformed)
levels(age_transformed)[1] = "Young-Old"
levels(age_transformed)[2] = "Med-Old"
levels(age_transformed)[3] = "Old"
levels(age_transformed)[4] = "Old-Old"