简体   繁体   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)

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.

相关问题 如何创建for循环来计算向量中落在设定边界之间的值的数量? - How can I create a for-loop to count the number of values within a vector that fall between a set boundary? 计算 R 中单独数据框中某个日期范围内的条目数 - Count the number of entries that fall within a range of dates in a separate dataframe in R 如何在R的最小值的一定范围内找到向量中的值数? - How can I find the number of values in a vector within a certain range of the minimum with R? R 向量计数每个日期范围内的日期数 - R vector count number of dates within range of each date 计算R范围内的向量值数量 - Count number of vector values in range with R 在 R 中使用 apply() 计算每列范围内的单元格数 - Using apply() in R to count the number of cells within a range for each column 如何计算R中向量中按顺序排列的相同元素的数量? - How to count the number of same elements which are in order in a vector in R? 使用 R,如何根据范围内的数字为新列分配值? - With R, how do i assign values to a new column based on numbers that fall within a range? 如何计算 R 中给定范围内的值以上的实例数? - How to count number of instances above a value within a given range in R? 如何使用R将向量中的特定数字相乘 - How can i multiply specific number in vector using R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM