将连续数值转换为由间隔定义的离散类别我有一个具有连续数值变量的数据框架,即以月份为单位的年龄(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函数,但我无法处理它,因为我的目的是对其进行离散/分类。
2 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
cut
cut
# Some example datarota2 <- data.frame(age_mnth = 1:170)# Your way of doing things to compare againstrota2$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 cutrota2$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)
蛊毒传说
TA贡献1895条经验 获得超3个赞
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) ) ]
- 2 回答
- 0 关注
- 719 浏览
添加回答
举报
0/150
提交
取消