Count number of distinct values in a vector

uniqueN function from data.table is equivalent to length(unique(group)). It is also several times faster on larger datasets, but not so much on your example.

library(data.table)
library(microbenchmark)

xSmall <- sample.int(25, 1000, TRUE)
xBig <- sample.int(2500, 100000, TRUE)
microbenchmark(length(unique(xSmall)), uniqueN(xSmall), 
               length(unique(xBig)), uniqueN(xBig))

#Unit: microseconds
#                    expr      min        lq       mean    median        uq      max neval cld
#1 length(unique(xSmall))   17.742   24.1200   34.15156   29.3520   41.1435  104.789   100 a  
#2        uniqueN(xSmall)   12.359   16.1985   27.09922   19.5870   29.1455   97.103   100 a  
#3   length(unique(xBig)) 1611.127 1790.3065 2024.14570 1873.7450 2096.5360 3702.082   100 c
#4          uniqueN(xBig)  790.576  854.2180  941.90352  896.1205  974.6425 1714.020   100 b 

Here are a few ideas, all points towards your solution already being very fast. length(unique(x)) is what I would have used as well:

x <- sample.int(25, 1000, TRUE)

library(microbenchmark)
microbenchmark(length(unique(x)),
               nlevels(factor(x)),
               length(table(x)),
               sum(!duplicated(x)))
# Unit: microseconds
#                 expr     min       lq   median       uq      max neval
#    length(unique(x))  24.810  25.9005  27.1350  28.8605   48.854   100
#   nlevels(factor(x)) 367.646 371.6185 380.2025 411.8625 1347.343   100
#     length(table(x)) 505.035 511.3080 530.9490 575.0880 1685.454   100
#  sum(!duplicated(x))  24.030  25.7955  27.4275  30.0295   70.446   100

I have used this function

length(unique(array))

and it works fine, and doesn't require external libraries.


You can use rle from base package

  x<-c(1,2,3,1,2,3,4,6)
  length(rle(sort(x))$values)

rle produces two vectors (lengths and values ). The length of values vector gives you the number of unique values.