R Programming: Count Number of values in a Range in a given Vector
Write a R program to count number of values in a range in a given vector.
Sample Solution :
R Programming Code :
# Create a vector 'v' with a sequence of values
v = c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90)
# Print a message indicating the original vector
print("Original vector:")
# Print the original vector 'v'
print(v)
# Count the number of values in vector 'v' that are greater than 10 and less than 50
ctr = sum(v > 10 & v < 50)
# Print a message indicating the result of the count
print("Number of vector values between 10 and 50:")
# Print the count of values that are within the specified range
print(ctr)
Output:
[1] "Original vector:" [1] 0 10 20 30 40 50 60 70 80 90 [1] "Number of vector values between 10 and 50:" [1] 3
Explanation:
- Create a vector:
- v = c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90)
A vector v is created containing a sequence of numeric values from 0 to 90. - Print the original vector:
- print("Original vector:")
Prints a message indicating the next output will display the original vector. - Display the vector:
- print(v)
Displays the elements of the vector v. - Count values in a range:
- ctr = sum(v > 10 & v < 50)
The code checks which elements of v are greater than 10 and less than 50. The sum() function counts how many elements meet this condition, storing the result in ctr. - Print message (Count result):
- print("Number of vector values between 10 and 50:")
Prints a message indicating the result of the count will follow. - Print the count of values:
- print(ctr)
Displays the total count of values in v that are between 10 and 50. In this case, the count is 3.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to concatenate a vector.
Next: Write a R program to convert two columns of a data frame to a named vector.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics