Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

r - Count number of distinct values in a vector

I have a vector of scalar values of which I'm trying to get: "How many different values there are".

For instance in group <- c(1,2,3,1,2,3,4,6) unique values are 1,2,3,4,6 so I want to get 5.

I came up with:

length(unique(group))

But I'm not sure it's the most efficient way to do it. Isn't there a better way to do this?

Note: My case is more complex than the example, consisting of around 1000 numbers with at most 25 different values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...