Rescale vector R

Suppose I have an integer vector, for example:

> x
[1]  1  1  1  4  4 13 13 14

I'm looking for an effective way to readjust the vector to the integer 1 to the maximum number of unique elements in R So the resulting vector will be:

1 1 1 2 2 3 3 4

It looks like a simple problem, but I can't find an effective way to do it In fact, this vector is very large (about 500)

Solution

Try to match (x, sort (unique (x)):

x <- sample(1:50,1e6,replace = TRUE)
benchmark(as.integer(factor(x)),match(x,sort(unique(x))),replications = 20,columns = c("test","elapsed","relative"))
#                        test elapsed relative
# 1     as.integer(factor(x))   18.44    10.36
# 2 match(x,sort(unique(x)))    1.78     1.00

identical(as.integer(factor(x)),sort(unique(x))))
# [1] TRUE
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>