[英]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)
。
Another base R solution is to use hist
, ie,另一个基本的 R 解决方案是使用
hist
,即,
hist(a,plot = FALSE,breaks = seq(10,70,by=10))$counts
# [1] 1 2 2 0 2 1
Here is the solution:这是解决方案:
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
We can use cut
with table
可以使用
table
cut
table(cut(a, breaks = c(-Inf, seq(10, 70, by = 10), Inf)))
Or another option is或者另一种选择是
table(findInterval, seq(10, 70, by = 10)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.