繁体   English   中英

如何使用 r 计算向量中落在特定范围内的元素数量?

[英]How can I count the number of elements in a vector that fall within a particular range using r?

假设我们有一个向量a = (10,23,57,37,59,25,63,33)并且我们想要计算区间10-19,20-29,30-39,40-49,50-59,60-69的频率10-19,20-29,30-39,40-49,50-59,60-69 . 输出应为向量形式,在本例中为(1,2,2,2,1)

另一个基本的 R 解决方案是使用hist ,即,

hist(a,plot = FALSE,breaks = seq(10,70,by=10))$counts
# [1] 1 2 2 0 2 1

这是解决方案:

a <- c(10, 23, 57, 37, 59, 25, 63, 33)
low_val  <- 10
high_val <- 70
a_breaks <- seq(low_val, high_val, 10)
res <- cut(a, a_breaks, include.lowest = T)
as.vector(table(res))
[1] 1 2 2 0 2 1

可以使用table cut

table(cut(a, breaks = c(-Inf, seq(10, 70, by = 10), Inf)))

或者另一种选择是

table(findInterval, seq(10, 70, by = 10)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM