将连续数值转换为由间隔定义的离散类别

时间:2012-11-26 05:22:57

标签: r r-faq

我有一个带有连续数字变量的数据框,年龄以月为单位(age_mnths)。我想创建一个新的离散变量,其年龄类别基于年龄间隔。

# Some example data
rota2 <- data.frame(age_mnth = 1:170)

我已创建基于ifelse的程序(如下),但我相信有可能提供更优雅的解决方案。

rota2$age_gr<-ifelse(rota2$age_mnth < 6, rr2 <- "0-5 mnths",

   ifelse(rota2$age_mnth > 5 & rota2$age_mnth < 12, rr2 <- "6-11 mnths",

          ifelse(rota2$age_mnth > 11 & rota2$age_mnth < 24, rr2 <- "12-23 mnths",

                 ifelse(rota2$age_mnth > 23 & rota2$age_mnth < 60, rr2 <- "24-59 mnths",

                        ifelse(rota2$age_mnth > 59 & rota2$age_mnth < 167, rr2 <- "5-14 yrs",

                              rr2 <- "adult")))))

我知道有cut功能,但我无法处理它以便我进行离散/分类。

2 个答案:

答案 0 :(得分:39)

如果您有理由不想使用cut,那么我不明白为什么。 cut可以正常使用您想要的内容

# Some example data
rota2 <- data.frame(age_mnth = 1:170)
# Your way of doing things to compare against
rota2$age_gr<-ifelse(rota2$age_mnth<6,rr2<-"0-5 mnths",
                     ifelse(rota2$age_mnth>5&rota2$age_mnth<12,rr2<-"6-11 mnths",
                            ifelse(rota2$age_mnth>11&rota2$age_mnth<24,rr2<-"12-23 mnths",
                                   ifelse(rota2$age_mnth>23&rota2$age_mnth<60,rr2<-"24-59 mnths",
                                          ifelse(rota2$age_mnth>59&rota2$age_mnth<167,rr2<-"5-14 yrs",
                                                 rr2<-"adult")))))

# Using cut
rota2$age_grcut <- cut(rota2$age_mnth, 
                       breaks = c(-Inf, 6, 12, 24, 60, 167, Inf), 
                       labels = c("0-5 mnths", "6-11 mnths", "12-23 mnths", "24-59 mnths", "5-14 yrs", "adult"), 
                       right = FALSE)

答案 1 :(得分:14)

rota2$age_gr<-c( "0-5 mnths", "6-11 mnths", "12-23 mnths", "24-59 mnths", "5-14 yrs",
                 "adult")[
           findInterval(rota2$age_mnth , c(-Inf, 5.5, 11.5, 23.5, 59.5, 166.5, Inf) ) ]