2012-11-26 3 views
13

저는 연속적인 숫자 변수를 가진 데이터 프레임을 가지고 있습니다. 나이는 월 (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 기능이하지만 난/분류합니다을 이산화 내 목적으로 다룰 수 없었다 알고있다.

+0

여기에 기본적인 오류가 그것은'보다 약간 다르다 "예"와 "아니오"매개 변수 –

답변

30

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) 
10
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)) ] 
+1

에 대한 값의 할당 연산자를 사용하는 것입니다 수행 할 작업을 cut을 위해 잘 작동합니다 구간이 왼쪽에서 닫히고 오른쪽에서 열리는 점에서 다르게 지정되지 않는 한 '잘라 내기'입니다. –

+1

하지만 항상 오른쪽에서 닫히고 왼쪽에서 열리는 findInterval 버전을 작성할 수 있습니다. - http://stackoverflow.com/questions/13482872/findinterval-with-right-closed-intervals – Dason

관련 문제