Rescale Vector R

后端 未结 2 1765
走了就别回头了
走了就别回头了 2021-01-19 08:21

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 vecto

2条回答
  •  礼貌的吻别
    2021-01-19 08:59

    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
    

提交回复
热议问题