# 重新调整矢量R(Rescale Vector R)

``` 假设我有一个整数向量，例如：
```> x
[1]  1  1  1  4  4 13 13 14
```
我在R中寻找一种有效的方法来将矢量重新调整为整数1，以将元素的唯一数量最大化。 因此得到的向量将是：
```1 1 1 2 2 3 3 4
```
看起来像一个简单的问题，但我很难找到一个有效的方法来做到这一点。 在实践中，这个向量很大（大约500）。 Suppose I have a vector of integers such as:
```> x
[1]  1  1  1  4  4 13 13 14
```
I am looking for an efficient way in R to rescale the vector to integers 1 to the max of the unique number of elements. Therefore the resulting vector would be:
```1 1 1 2 2 3 3 4
```
Seems like a simple problem but I'm having trouble finding an efficient way to do it. In practice this vector is large (around 500).原文：https://stackoverflow.com/questions/13434204```

## 最满意答案

``` 尝试`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)), match(x, sort(unique(x))))
# [1] TRUE
```Try `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)), match(x, sort(unique(x))))
# [1] TRUE
``````
2012-11-17