9

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

我有这样的想法:

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

3 回答 3

18
x <- rnorm(100,10,10)
cut(x,c(-Inf,0,5,6,10,Inf))
于 2010-04-15T18:00:33.973 回答
12

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

我更喜欢使用shingle,来自Lattice Package

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

你像这样使用木瓦

# 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
于 2010-04-15T18:21:16.950 回答
2

我们可以使用smart_cutfrom package 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

更多关于 cutr 和 smart_cut

于 2018-10-05T22:39:33.770 回答