重新缩放向量 R [英] Rescale Vector R

查看:26
本文介绍了重新缩放向量 R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个整数向量,例如:

Suppose I have a vector of integers such as:

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

我正在 R 中寻找一种有效的方法来将向量重新缩放为整数 1 到唯一元素数量的最大值.因此得到的向量将是:

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

似乎是一个简单的问题,但我找不到有效的方法来解决这个问题.实际上,这个向量很大(大约 500).

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).

推荐答案

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

这篇关于重新缩放向量 R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆