R语言 用R计算范围内的向量值的数量
在这篇文章中,我们将看到如何在R中计算给定范围内存在的向量值的数量。为了实现这一功能,我们可以遵循以下方法。
方法
- 创建向量
- 设置范围
- 遍历向量
- 检查在范围内的元素
- 添加它们
- 显示总和
下面给出了使用这种方法的实现。
例1 :
# declaring a integer point vector
vec <- c(1,12,3,14,-1,-3)
# specifying the range to check the element in
min_range = -2
max_range = 8
# computing the size of the vector
size = length(vec)
# declaring sum =0 as the count of elements in range
sum = 0
# looping over the vector elements
for(i in 1:size)
{
# check if elements lies in the range provided
if(vec[i]>=min_range && vec[i]<=max_range)
# incrementing count of sum if condition satisfied
sum =sum+1
}
print ("Sum of elements in range : ")
print (sum)
输出
[1] “范围内的元素之和:”
[1] 3
例2 :
# declaring a integer point vector
vec <- c(1,12,3,14,-1,-3,0.1)
# specifying the range to check the element in
min_range = -2
max_range = 8
print ("Sum of elements in specified range : ")
# and operator check if the element is less than
# max range and greater than min range
sum(vec>min_range & vec<max_range)
输出
[1] “Sum of elements in specified range : “
[1] 4
然而,如果向量中的任何元素是NA,那么sum()方法的输出就会返回NA。可以通过指定na.rm=TRUE来忽略它。
例3 :
# declaring a integer point vector
vec <- c(1,12,3,14,NA,-3,0.1)
# specifying the range to check the element in
min_range = -2
max_range = 8
print ("Sum of elements in specified range without ignoring NA: ")
# and operator check if the element is less than
# max range and greater than min range
sum(vec>min_range & vec<max_range)
print ("Sum of elements in specified range ignoring NA: ")
sum(vec>min_range & vec<max_range,na.rm=TRUE)
输出
[1] “Sum of elements in specified range without ignoring NA: “
[1] NA
[1] “Sum of elements in specified range ignoring NA: “
[1] 3