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

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

我有一个具有连续数值变量的数据框架,即以月份为单位的年龄(Age_Mnths)。我想做一个新的离散变量,基于年龄间隔的年龄类别。

# Some example datarota2 <- 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函数,但我无法处理它,因为我的目的是对其进行离散/分类。


墨色风雨
浏览 692回答 2
2回答

梦里花落0921

如果有什么原因你不想用cut那我就不明白为什么。cut会对你想做的事情很好#&nbsp;Some&nbsp;example&nbsp;datarota2&nbsp;<-&nbsp;data.frame(age_mnth&nbsp;=&nbsp;1:170)#&nbsp;Your&nbsp;way&nbsp;of&nbsp;doing&nbsp;things&nbsp;to&nbsp;compare&nbsp;againstrota2$age_gr<-ifelse(rota2$age_mnth <6,rr2<-"0-5&nbsp;mnths", &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ifelse(rota2$age_mnth>5&rota2$age_mnth<12,rr2<-"6-11&nbsp;mnths", &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb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sp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;breaks&nbsp;=&nbsp;c(-Inf,&nbsp;6,&nbsp;12,&nbsp;24,&nbsp;60,&nbsp;167,&nbsp;Inf),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;labels&nbsp;=&nbsp;c("0-5&nbsp;mnths",&nbsp;"6-11&nbsp;mnths",&nbsp;"12-23&nbsp;mnths",&nbsp;"24-59&nbsp;mnths",&nbsp;"5-14&nbsp;yrs",&nbsp;"adult"),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;right&nbsp;=&nbsp;FALSE)

蛊毒传说

rota2$age_gr<-c(&nbsp;"0-5&nbsp;mnths",&nbsp;"6-11&nbsp;mnths",&nbsp;"12-23&nbsp;mnths",&nbsp;"24-59&nbsp;mnths",&nbsp;"5-14&nbsp;yrs", &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"adult")[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;findInterval(rota2$age_mnth&nbsp;,&nbsp;c(-Inf,&nbsp;5.5,&nbsp;11.5,&nbsp;23.5,&nbsp;59.5,&nbsp;166.5,&nbsp;Inf)&nbsp;)&nbsp;]
打开App,查看更多内容
随时随地看视频慕课网APP