Reputation: 21
I need a line of code that will search a vector of numbers and return the number of occurrences. For Example
a=c(15,32,27, 63, 15,99, 32,32)
dup=unique(a[duplicated(V.Ints)])
len=length(unique(duplicated(dup)))
I get:
> dup
#[1] 15, 32
> len
#[1] 2
but what I need is:
> dup
#[1] 15, 32
> len
#[1] 5
Thank you!
Upvotes: 2
Views: 154
Reputation: 21641
Arun's suggestion in the comments is the way to go:
> sum(a %in% c(15,32))
#[1] 5
For more general usage:
sum(a %in% unique(a[duplicated(a)]))
Or a one-liner in the spirit of Mr Flick's approach:
sum(a %in% names(which(table(a) > 1)))
Upvotes: 3
Reputation: 99371
Another variation is to grab all the duplicated values then use length()
for len
and unique()
for dup
x <- a[duplicated(a) | duplicated(a, fromLast=TRUE)]
length(x)
# [1] 5
unique(x)
# [1] 15 32
Upvotes: 2
Reputation: 206566
You can count frequencies with
table(a)
# a
# 15 27 32 63 99
# 2 1 3 1 1
You can filter to find only the duplicates
Filter(function(x) x>1, table(a))
# a
# 15 32
# 2 3
names(Filter(function(x) x>1, table(a)))
# [1] "15" "32"
and you can take the sum to find the total length of duplicates
sum(Filter(function(x) x>1, table(a)))
# [1] 5
Upvotes: 2