Count Duplicates In Vector In R

Viewed 134
group=c(1,1,2,2,3,4,4,5,5,6)

I am wishing to generate an output that looks like:

dup:4

nodup: 2

Basically I want to count how many values are duplicated 'dup' and count how many are not 'nodup'

4 Answers

Here is an option, get the frequency count of values with table, convert to logical > 1 and then do a table again

table(table(group) > 1)

If we need the label names as 'dup', 'nodup'

table(c('nodup', 'dup')[1 + (table(group) > 1)])
#    dup nodup 
#    4     2 

Another base R solution using duplicated + unique

dup <- sum(duplicated(group))
nodup <- length(unique(group))-dup

such that

> dup
[1] 4
> nodup
[1] 2
library(dplyr)
data.frame(group) %>%
    count(group) %>%
    count(dup = n > 1)

Also a base R option:

table(rle(sort(group))$lengths > 1)

FALSE  TRUE 
    2     4 
Related