0

If I have a vector

vec = c('a','a','a','b','b','c','c','c','c','c')

Is there a simple way to find the least occurring element in vec? Thanks!

Edit: is there a simple way to do it with characters?

Michael
  • 7,087
  • 21
  • 52
  • 81

2 Answers2

4

This should work, even if more than one of the elements is tied as the least frequent item:

vec = c(1,1,1,2,2,3,3,3,3,3)

f <- table(vec)
as.numeric(names(f[f == min(f)]))
# [1] 2
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
3
table(vec)[which.min(table(vec))]

(In all likelihood a duplicate, although I have searched. Found what seemed to be similar on the max side: Create a variable capturing the most frequent occurence by group Maybe it sounds familiar to that one 'cuz I posted an answer?)

Community
  • 1
  • 1
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • I was thinking of comparing elapsed time for this vs. `min(hist(charto8bit(vec))$counts)` but thought that would be a candidate for thedailywtf's Code SOD :-) – Carl Witthoft Jan 10 '12 at 19:16