Count number of vector values in range with R
Last Updated :
28 Sep, 2021
In this article, we will see how to count the number of vector values present in the given range in R. To achieve this functionality we can follow the following approach.
Approach
- Create vector
- Set range
- Iterate through the vector
- Check for elements that are within the range
- Add them
- Display sum
Implementation using this approach is given below.
Example 1:
R
vec <- c (1,12,3,14,-1,-3)
min_range = -2
max_range = 8
size = length (vec)
sum = 0
for (i in 1:size)
{
if (vec[i]>=min_range && vec[i]<=max_range)
sum =sum+1
}
print ( "Sum of elements in range : " )
print (sum)
|
Output
[1] “Sum of elements in range : “
[1] 3
Example 2:
R
vec <- c (1,12,3,14,-1,-3,0.1)
min_range = -2
max_range = 8
print ( "Sum of elements in specified range : " )
sum (vec>min_range & vec<max_range)
|
Output
[1] “Sum of elements in specified range : “
[1] 4
However, if any of the elements of the vector is NA, then sum() method returns NA as the output. It can be ignored by specifying na.rm=TRUE.
Example 3:
R
vec <- c (1,12,3,14, NA ,-3,0.1)
min_range = -2
max_range = 8
print ( "Sum of elements in specified range without ignoring NA: " )
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 )
|
Output
[1] “Sum of elements in specified range without ignoring NA: “
[1] NA
[1] “Sum of elements in specified range ignoring NA: “
[1] 3
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...