Search code examples
rrecode

How to recode continuous age in age categories and create a new variable at the same time


I have an age variable and i need to recode it into categories. I've see both of these questions asked, but the answers only seem to create something in memory. When i open the data.table, the new categorical variable is not there. I can't see it and i can't subset with it. But i can run a frequency on it. But i need it to be its own variable.

R code to categorize age into group/ bins/ breaks

Convert Age variable into ordinal variable

How do i convert a continuous variable into a factor and have a tangible variable afterwards? Or, how do i take whatever is being created in memory, and make it real?

`setDT(LSSCM)[client_age <17, agegroup := "0-17"]`
`LSSCM[client_age >=18 & client_age <=24, agegroup := "18-24"]`
`LSSCM[client_age >=25 & client_age <=30, agegroup := "25-30"]`
`LSSCM[client_age >=31 & client_age <=39, agegroup := "31-39"]`
`LSSCM[client_age >=40 & client_age <=54, agegroup := "40-54"]`
`LSSCM[client_age >=55 & client_age <=64, agegroup := "55-64"]`
`LSSCM[client_age >=65 & client_age <=75, agegroup := "65-75"]`
`LSSCM[client_age >=76, agegroup := "76+"]`

Also tried.

LSSCM$age_cat <- case_when(LSSCM$client_age <= 17 ~ '0-17',
                           between(LSSCM$client_age, 18, 24) ~ '18-24',`
                           between(LSSCM$client_age, 25, 30) ~ '25-30',`
                           between(LSSCM$client_age, 31, 39) ~ '31-39',`
                           between(LSSCM$client_age, 40, 54) ~ '40-54',`
                           between(LSSCM$client_age, 55, 64) ~ '55-64',`
                           between(LSSCM$client_age, 65, 75) ~ '65-75',`
                           LSSCM$client_age >= 76 ~ '76+')`

Solution

  • Simply assign the result of your preferred solution into a column in the data.frame. For example:

    df$agegroups<-cut(df$ages, breaks=c(20, 30, 40, 50), right = FALSE)
    

    For example:

    df<-data.frame(age = c(55, 60, 65, 70, 75, 80, 85, 90, 95))
    df
      age
    1  55
    2  60
    3  65
    4  70
    5  75
    6  80
    7  85
    8  90
    9  95
    df$age_cat<-cut(df$age, breaks=c(0,17,24,30,39,54,64,75), right = FALSE)
    df
      age age_cat
    1  55 [54,64)
    2  60 [54,64)
    3  65 [64,75)
    4  70 [64,75)
    5  75    <NA>
    6  80    <NA>
    7  85    <NA>
    8  90    <NA>
    9  95    <NA>