Suppose I have a vector, and I do not know, a priori, its unique elements (here: 1 and 2).
vec <- c(1, 1, 1, 2, 2, 2, 2)
I was interested to know if there is a better way (or an elegant way) to get the number of unique elements in vec , i.e. the same result as table(vec) . It does not matter if its data.frame file or named vector has it.
R> table(vec) vec 1 2 3 4
Reason: I was curious to find out if there is a better way. In addition, I noticed that there is a for loop in the base implementation (in addition to calling .C). I donβt know if this is a big problem, but when I do something like
R> table(rep(1:1000,100000))
R takes a lot of time. I am sure this is due to the huge amount of 100,000. But is there any way to do this faster?
EDIT This is also a good job in addition to Chase's answer.
R> rle(sort(sampData))
source share