R Program to count number of values in a range in a given vector

How to count the number of values in a range in a given vector

Here we are explaining how to write an R program to count the number of values in a range in a given vector. Here we are using a built-in function sum for this calculation. The sum() function returns the sum of all the values present in its arguments. And its syntax is

sum(x, na.rm = FALSE) – where x is a vector

How to count the number of values in a range using the R Program

Given below are the steps which are used in the R program to count the number of values in a range in a given vector. In this R program, variable A is used for assigning vector values. The variable count is used for assigning the count of values. In the function sum, we have to specify the limit of values for finding the count of values. It is given as a sum(A> 20 & A < 70) for getting the count of values in between values 20 and 70.

ALGORITHM

  • STEP 1: take the vector values into variable A
  • STEP 2: Consider count variable as the result value
  • STEP 4: First print the original vectors
  • STEP 5: Find the count as count=sum(A> 20 & A < 70)
  • STEP 6: The count of values between 20 and 70 is assigned to a variable count
  • STEP 7: print the variable count as result value

R Source Code

A = c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90)

print("Original vector:")
## [1] "Original vector:"
print(A)
##  [1]  0 10 20 30 40 50 60 70 80 90
count =  sum(A> 20 & A < 70)

print("Number of vector values between 20 and 70:")
## [1] "Number of vector values between 20 and 70:"
print(count)
## [1] 4

R Source Code

A = c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90)

print("Original vector:")
## [1] "Original vector:"
print(A)
##  [1]  0 10 20 30 40 50 60 70 80 90
count =  sum(A > 30 & A < 60)

print("Number of vector values between 20 and 70:")
## [1] "Number of vector values between 20 and 70:"
print(count)
## [1] 2