我的数据有一个ID列,我想将ID重命名为排名.换句话说,我想重命名所有35-> 1,所有39-> 2,所有66-> 3所有77-> 4和所有90-> 5来自以下数据.
我试图使用秩函数但我无法处理两个并列值.我想为id中的两个绑定值给出相同的数字(例如,所有35得到1).
如何将每个ID更改为升序号?
ID
--
35
35
35
35
39
39
39
66
66
66
66
77
77
90
90
90
Run Code Online (Sandbox Code Playgroud)
您可以利用因子变量将从1开始的顺序值分配给排序数据:
ID <- c(35, 35, 35, 35, 39, 39, 39, 66, 66, 66, 66, 77, 77, 90, 90, 90)
as.numeric(as.factor(ID))
# [1] 1 1 1 1 2 2 2 3 3 3 3 4 4 5 5 5
Run Code Online (Sandbox Code Playgroud)
事实证明这比其他提议的方法要快得多(即使考虑到unique(vect)Vincent的sapply功能):
library(microbenchmark)
ID <- rnorm(10000)
microbenchmark(as.numeric(as.factor(ID)), funPascal(ID), funVincent(ID))
# Unit: milliseconds
# expr min lq median uq max neval
# as.numeric(as.factor(ID)) 23.94388 24.64445 25.17679 25.8263 34.68806 100
# funPascal(ID) 2754.19694 2822.37356 2875.71998 2929.9071 3471.90363 100
# funVincent(ID) 416.58985 438.13800 445.29766 458.8043 769.44278 100
Run Code Online (Sandbox Code Playgroud)