我有一个包含一列整数的dataframe,我想用它作为一个引用来创建一个新的分类变量。我想将变量分成三组,并自己设置范围(即0-5,6-10等)。我尝试了cut,但它根据正态分布将变量划分为组,并且我的数据是正确的。我也尝试过使用if/then语句,但这输出了一个true/false值,并且我想保留我的原始变量。我确信有一种简单的方法可以做到这一点,但我似乎找不到办法。有什么建议可以用一种简单的方法快速完成这件事吗?
我的想法是这样的:
x x.range
3 0-5
4 0-5
6 6-10
12 11-15发布于 2010-04-16 02:21:17
据我所知,Ian的回答(cut)是最常见的方法。
我更喜欢使用包中的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发布于 2010-04-16 02:00:34
x <- rnorm(100,10,10)
cut(x,c(-Inf,0,5,6,10,Inf))发布于 2018-10-06 06:39:34
我们可以使用cutr包中的smart_cut
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-15https://stackoverflow.com/questions/2647639
复制相似问题