用 R 计算范围内向量值的数量
在本文中,我们将看到如何计算 R 中给定范围内存在的向量值的数量。要实现此功能,我们可以遵循以下方法。
方法
- 创建矢量
- 设定范围
- 遍历向量
- 检查范围内的元素
- 添加它们
- 显示总和
下面给出使用这种方法的实现。
示例 1:
R
# 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)
R
# 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 rannge and greater than min range
sum(vec>min_range & vec
R
# 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 rannge and greater than min range
sum(vec>min_range & vecmin_range & vec
输出
[1] “Sum of elements in range : “
[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 rannge and greater than min range
sum(vec>min_range & vec
输出
[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 rannge and greater than min range
sum(vec>min_range & vecmin_range & vec
输出
[1] “Sum of elements in specified range without ignoring NA: “
[1] NA
[1] “Sum of elements in specified range ignoring NA: “
[1] 3