0

I'm trying to create a bin that looks like "<18, 18-24, 25-34, 35-44, 45-54, 55-64, 65+". I'm able to create evenly spaced ranges (25-34, 35-44...65+) but I can't figure out how to add the first two ranges (<18, 18-24). Here's the code that I found:

age.cat <- function(x, lower = 0, upper, by = 10,
                   sep = "-", above.char = "+") {

 labs <- c(paste(seq(lower, upper - by, by = by),
                 seq(lower + by - 1, upper - 1, by = by),
                 sep = sep),
           paste(upper, above.char, sep = ""))

 cut(floor(x), breaks = c(seq(lower, upper, by = by), Inf),
     right = FALSE, labels = labs)
}

Any help would be much appreciated. Thanks

enson
  • 1
  • I'd create separate column in data frame such as `df$col2[df$col1 < 18] <- "[0-18]"`. Or something along the lines. And so on for each bracket. – statespace Mar 06 '15 at 07:09
  • @A.Val. OP would like "<18", not "[0-18]". –  Mar 06 '15 at 07:11
  • 1
    I assumed that it is demographic data, hence the age bracket below 18 would be 0-18. But that is not the point, he can write any string he wants, I merely gave an example. – statespace Mar 06 '15 at 07:13

2 Answers2

0

You want

library(Hmisc)
cut2(age, cuts=c(19, 25, 35, 45, 55, 65))
animalito
  • 382
  • 2
  • 7
0

The cut function has a lot of parameters that determine how hte cuts are made which get reflected in the output notation. Intervals need to be either all right-closed (the default) or all left closed:

vals <- 1:100
 cats <-cut( vals, breaks = c(0,18,seq(25,65,by=10),Inf))
 table(cats)
#----------
cats
  (0,18]  (18,25]  (25,35]  (35,45]  (45,55]  (55,65] (65,Inf] 
      18        7       10       10       10       10       35

Then modify the levels attribute:

 levels(cats) <-  sub("\\,Inf\\]", "+", sub("\\(0\\,", "<", levels(cats) ))
 table(cats)
#------------
cats
   <18] (18,25] (25,35] (35,45] (45,55] (55,65]    (65+ 
     18       7      10      10      10      10      35 

I agree with @animalito that the Hmisc::cut2 function has defaults that are more to my liking.

IRTFM
  • 258,963
  • 21
  • 364
  • 487