根据范围在R中创建分类变量

时间:2010-04-15 17:36:24

标签: r r-faq

我有一个带有整数列的数据框,我想用它作为参考来创建一个新的分类变量。我想将变量分成三组并自己设置范围(即0-5,6-10等)。我尝试cut,但是根据正态分布将变量分成组,我的数据是正确的。我也尝试使用if / then语句,但这会输出一个真/假值,我想保留原始变量。我确信有一种简单的方法可以做到这一点,但我似乎无法弄明白。有关简单方法的任何建议吗?

我有这样的想法:

x   x.range
3   0-5
4   0-5
6   6-10
12  11-15

3 个答案:

答案 0 :(得分:17)

x <- rnorm(100,10,10)
cut(x,c(-Inf,0,5,6,10,Inf))

答案 1 :(得分:12)

据我所知,伊恩的回答( cut )是最常见的做法。

我更喜欢使用 Lattice 包中的 shingle

指定分箱间隔的参数对我来说似乎更直观一些。

你像这样使用 shingle

# mock some data
data = sample(0:40, 200, replace=T)

a = c(0, 5);b = c(5,9);c = c(9, 19);d = c(19, 33);e = c(33, 41)

my_bins = matrix(rbind(a, b, c, d, e), ncol=2)

# returns: (the binning intervals i've set)
        [,1] [,2]
 [1,]    0    5
 [2,]    5    9
 [3,]    9   19
 [4,]   19   33
 [5,]   33   41

shx = shingle(data, intervals=my_bins)

#'shx' at the interactive prompt will give you a nice frequency table:
# Intervals:
   min max count
1   0   5    23
2   5   9    17
3   9  19    56
4  19  33    76
5  33  41    46

答案 2 :(得分:1)

我们可以使用软件包smart_cut中的cutr

devtools::install_github("moodymudskipper/cutr")
library(cutr)

x <- c(3,4,6,12)

要从1开始以长度5的间隔切割:

smart_cut(x,list(5,1),"width" , simplify=FALSE)
# [1] [1,6)   [1,6)   [6,11)  [11,16]
# Levels: [1,6) < [6,11) < [11,16]

要准确获取您要求的输出:

smart_cut(x,c(0,6,11,16), labels = ~paste0(.y[1],'-',.y[2]-1), simplify=FALSE, open_end = TRUE)
# [1]   0-5   0-5  6-10 11-15
# Levels:   0-5 <  6-10 < 11-15

more on cutr and smart_cut