Open In App

Count repeated values in R

Last Updated : 30 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how we can count the repeated values in R programming language. 

We will be using the table() function along with which() and length() functions to get the count of repeated values. The table() function in R Language is used to create a categorical representation of data with the variable name and the frequency in the form of a table.

Syntax: table(x)

Parameters:
x: Object to be converted

Using condition table(v>1) will return the boolean values, it will return TRUE for the values which have a frequency of greater than 1 else it will return false. Here, we have used (v>1) as we want those elements whose frequency is greater than 1. On passing it as an argument in which() function it will return the elements(along with their indexes) which are repeated more than once. which(): This function returns the index of the element which satisfies the condition given in the parameters. 

Use the length() function to count the number of elements returned by the which() function, as which function returns the elements that are repeated more than once. The length() function in R Language is used to get or set the length of a vector (list) or other objects.

Syntax: 

length(which(table(v)>1))

Example 1:

R




# sample vector
v <- c(1,1,1,1,1,5,2,3,4,5,3,7,8,9,5)
v
  
print("Count of repeated values")
length(which(table(v)>1))


Output:

 [1] 1 1 1 1 1 5 2 3 4 5 3 7 8 9 5

[1] “Count of repeated values”

[1] 3

Example 2:

R




v <- c(c(5:15),c(10:12),5,5,6,7)
v
  
print("Count of repeated values")
length(which(table(v)>1))


Output:

 [1]  5  6  7  8  9 10 11 12 13 14 15 10 11 12  5  5  6  7

[1] “Count of repeated values”

[1] 6

Printing the repetitive elements

Using condition table(v>1) will return the boolean values, it will return TRUE for the values which have a frequency of more than 1 else it will return false. On passing it as an argument in which() function it will return the elements(along with their indexes) which are repeated more than once. which(): This function returns the index of the element which satisfies the condition given in the parameters.

Syntax

which(table(v)>1)

Example 1:

R




v <- c(c(5:15),c(10:12),5,5,6,7)
v
  
print("Elements which are repeated")
which(table(v)>1)


Output: 

 [1]  5  6  7  8  9 10 11 12 13 14 15 10 11 12  5  5  6  7

[1] “Elements which are repeated”

5  6  7 10 11 12

1  2  3  6  7  8 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads