下面是一个例子:
height
1 1.5
2 1.3
3 1.9
4 1.5
5 1.6
有1000个,高度从0到1.9不等。我想把它们分成三个层次:低、中、高。那么它们就是有序数据。
结果应该像这样:
height
1 medium
2 low
3 high
4 medium
5 medium
和摘要应该看起来像:
height
low: 203
medium: 723
high: 74
我尝试使用循环,但是"low, medium and high"是字符,而不是级别。下面是我如何做低的部分:
height_cuts = c(1.5,1.9)
for(i in 1:nrow(health.sample)){
if(is.na(health.sample$height[i])==FALSE){
if(health.sample$height[i] < height_cuts[1]){
health.sample$height[i] = low_h
}
}
}
cut(height, quantile(height, prob=c(203, 723, 74)/1000 ), labels=c("low", "medium", "high") )
cut
将很方便地删除您的数据。
# cut needs all endpoints explicitly specified, including outside bounds
height_cuts <- c(-Inf, 1.5, 1.9, Inf)
hcut <- cut(height, height_cuts, labels=c("low", "medium", "high"))
ETA:这将使间隔基于<=1.5, <=1.9。如果您希望间隔为<1.5, <1.9,请指定right=FALSE
:
hcut <- cut(height, height_cuts, right=FALSE, ...)
使用cut
:
cut(x$height, c(0,1.5,1.9,10), labels=c("low","med","high"), right=FALSE)
# [1] med low high med med