w3resource

Count the Occurrences of a specific value in a Vector in R Programming

R Programming: Vector Exercise-11 with Solution

Write a R program to count the specific value in a given vector.

Sample Solution :

R Programming Code :

# Create a numeric vector 'x' with elements 10, 20, 30, 20, 20, 25, 9, and 26
x = c(10, 20, 30, 20, 20, 25, 9, 26)

# Print a message indicating the display of the original vector
print("Original Vectors:")

# Print the contents of vector 'x'
print(x)

# Print a message indicating the count of the specific value 20 in the vector
print("Count specific value(20) in above vector:")

# Count the number of occurrences of the value 20 in vector 'x' and print the result
print(sum(x == 20))

Output:

[1] "Original Vectors:"
[1] 10 20 30 20 20 25  9 26
[1] "Count specific value(20) in above vector:"
[1] 3                         

Explanation:

  • x = c(10, 20, 30, 20, 20, 25, 9, 26): Creates a numeric vector x with the elements 10, 20, 30, 20, 20, 25, 9, and 26.
  • print("Original Vectors:"): Prints the label "Original Vectors:" to indicate that the following output will display the vector x.
  • print(x): Prints the contents of vector x.
  • print("Count specific value(20) in above vector:"): Prints the label "Count specific value(20) in above vector:" to indicate that the following output will show the count of the value 20 in vector x.
  • print(sum(x==20)): Counts the number of occurrences of the value 20 in vector x and prints the result. The sum(x==20) counts how many times the condition x==20 is TRUE.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to test whether a given vector contains a specified element.
Next: Write a R program to access the last value in a given vector.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-11.php