Reputation: 1243
I am trying to run function that will take one parameter, which is list of numbers, and count the duplicates.
Example:
number <- c(1, 1, 1, 2, 2, 4, 5)
In this case, the output will be 2, because only 1 and 2 have duplicates.
I know how to use for loop but not sure how to count duplicates.
count = 0
for (x in number){
...
}
Upvotes: 1
Views: 1206
Reputation:
This solution is written in Python.
import collections
number = [1,1,1,2,2,4,5]
x = collections.Counter(number)
len([i for i in x if x[i]>1])
It puts the numbers that appears more than once in a list and then counts how many elements are in that list.
Upvotes: 0
Reputation: 99371
Tabulate the values, then count how many of those are greater than one.
x <- c(1, 1, 1, 2, 2, 4, 5)
sum(tabulate(x) > 1)
# [1] 2
Or, if you're looking for straight runs of duplicates, rle
can be used as an alternative to tabulation.
with(rle(x), sum(lengths > 1))
# [1] 2
Upvotes: 4