bvowe
bvowe

Reputation: 3394

Count Duplicates In Vector In R

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'

Upvotes: 2

Views: 1051

Answers (5)

tonysdatamodels
tonysdatamodels

Reputation: 41

A slightly longer method using base R but more interpretable.

repeated_values <- duplicated(group)
table(repeated_values)

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 40171

Also a base R option:

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

FALSE  TRUE 
    2     4 

Upvotes: 1

d.b
d.b

Reputation: 32558

library(dplyr)
data.frame(group) %>%
    count(group) %>%
    count(dup = n > 1)

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 102770

Another base R solution using duplicated + unique

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

such that

> dup
[1] 4
> nodup
[1] 2

Upvotes: 1

akrun
akrun

Reputation: 887951

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 

Upvotes: 4

Related Questions