2012-11-26 4 views
13

Ho un frame di dati con una variabile numerica continua, età in mesi (age_mnths). Voglio creare una nuova variabile discreta, con categorie di età basate sugli intervalli di età.Converti valori numerici continui in categorie discrete definite da intervalli

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

Ho creato ifelse procedura basata (sotto), ma credo che ci sia una possibilità di soluzione più elegante.

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"))))) 

So che c'è cut funzione, ma non ho potuto fare con esso per il mio scopo per discretizzare/categorizzare.

+0

Un errore di fondo qui è l'uso dell'operatore di assegnazione dei valori per il "sì" e "no" parametri –

risposta

30

Se c'è un motivo per cui non si desidera utilizzare cut quindi non capisco perché. cut funzionerà bene per quello che si vuole fare

# 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

E 'un po' diverso rispetto a ' tagliare in quanto gli intervalli sono chiusi a sinistra e aperti a destra se non diversamente specificato. –

+1

Ma puoi sempre scrivere una versione di findInterval chiusa a destra e aperta a sinistra - http://stackoverflow.com/questions/13482872/findinterval-with-right-closed-intervals – Dason