R Program to count the specific value in a given vector


February 8, 2023, Learn eTutorial
951

How to count the specific value in a given vector using R programming?

In this R program, we have to count the specific value in a given vector. Here we are using a built-in function sum(). The sum() function helps to return the count of specific values in the vector. The syntax of sum is,

sum(x, na.rm = FALSE, …)

Where,

  • x is a vector

In this R program, we are printing the original vector values first, then we directly give the values to the built-in function. Finally, print the function result. Here we used variable A for assigning vector values.

ALGORITHM

STEP 1: Assign variable A with vector values

STEP 2: display the original values of a vector

STEP 3: Call the function sum of finding element count as sum(A==30)

STEP 4: print the result of the function

R Source Code

                                          A = c(20, 30, 30, 10, 30, 25, 30, 27)
print("Original Vectors:")
print(A)
print("Count specific value(30) in above vector:")
print(sum(A==30))

                                      

OUTPUT

[1] "Original Vectors:"
[1] 20, 30, 30, 10, 30, 25, 30, 27
[1] "Count specific value(30) in above vector:"
[1] 4