我有一个看起来像这样的矢量:
dataset <- c(4,7,9,1,10,15,18,19,3,16,10,16,12,22,2,23,16,17)
Run Code Online (Sandbox Code Playgroud)
我想创建四个虚拟类别,其中我通过自定义中断来连接连续数据集...例如:1:4,5:9,10:17,18:23.
输出虚拟类别的长度与原始连续向量的长度相同(在这种情况下为18),但现在每个分箱的虚拟变量只包含1或0.
Jos*_*ich 16
用途cut:
data.frame(dataset, bin=cut(dataset, c(1,4,9,17,23), include.lowest=TRUE))
Run Code Online (Sandbox Code Playgroud)
我同意约书亚,这cut是大多数人会想到的这项任务.我不喜欢它的默认值,更喜欢左边闭合间隔,并且正确设置它是一个小麻烦cut(尽管可以做到.幸运的是,我的虚弱大脑,Frank Harrell cut2在他的Hmisc中设计了一个函数我更喜欢的默认包.第三种选择是使用findInterval它特别适合你想要将结果用作另一个提取或选择过程的索引的问题.它的结果大致是你应用于as.numeric结果的结果cut:
require(Hmisc)
cut2(dataset, c(1,4,9,17,23) )
[1] [ 4, 9) [ 4, 9) [ 9,17) [ 1, 4) [ 9,17) [ 9,17) [17,23] [17,23] [ 1, 4) [ 9,17)
[11] [ 9,17) [ 9,17) [ 9,17) [17,23] [ 1, 4) [17,23] [ 9,17) [17,23]
Run Code Online (Sandbox Code Playgroud)
(请注意,findInterval除非用R替换最大值Inf为无穷大的保留字,否则将使用上限作为封闭端形成一个额外的间隔.)
findInterval(dataset, c( c(1,4,9,17,23) ) )
[1] 2 2 3 1 3 3 4 4 1 3 3 3 3 4 1 5 3 4
as.numeric( cut(dataset, c(1,4,9,17,Inf), include.lowest=TRUE))
[1] 1 2 2 1 3 3 4 4 1 3 3 3 3 4 1 4 3 3
as.numeric( cut(dataset, c(1,4,9,17,23), include.lowest=TRUE))
[1] 1 2 2 1 3 3 4 4 1 3 3 3 3 4 1 4 3 3
Run Code Online (Sandbox Code Playgroud)