如何在R中向矢量添加范围?

时间:2015-03-06 06:58:28

标签: r binning

我试图创建一个看起来像"< 18,18-24,25-34,35-44,45-54,55-64,65 +" 。我能够创建均匀间隔范围(25-34,35-44 ... 65+),但我无法弄清楚如何添加前两个范围(< 18,18-24) 。这是我找到的代码:

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

非常感谢任何帮助。感谢

2 个答案:

答案 0 :(得分:0)

你想要

library(Hmisc)
cut2(age, cuts=c(19, 25, 35, 45, 55, 65))

答案 1 :(得分:0)

剪切功能有很多参数可以确定如何进行剪切,这些参数会反映在输出表示法中。间隔需要全部关闭(默认)或全部关闭:

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

然后修改levels属性:

 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 

我同意@animalito的说法,Hmisc :: cut2函数的默认值更符合我的喜好。