See the Warning section of ?factor
:
(请参阅?factor
的警告部分:)
In particular, as.numeric
applied to a factor is meaningless, and may happen by implicit coercion.
(特别是, as.numeric
施加到一个因素是没有意义的,并且可以通过隐式强制发生。)
To transform a factor f
to approximately its original numeric values, as.numeric(levels(f))[f]
is recommended and slightly more efficient than as.numeric(as.character(f))
. (为了将因子f
转换为近似于其原始数值,建议使用as.numeric(levels(f))[f]
其效率要比as.numeric(as.character(f))
。)
The FAQ on R has similar advice .
(关于R的FAQ 也有类似的建议 。)
Why is as.numeric(levels(f))[f]
more efficent than as.numeric(as.character(f))
?
(为什么as.numeric(levels(f))[f]
比as.numeric(as.character(f))
更有效?)
as.numeric(as.character(f))
is effectively as.numeric(levels(f)[f])
, so you are performing the conversion to numeric on length(x)
values, rather than on nlevels(x)
values.
(as.numeric(as.character(f))
实际上是as.numeric(levels(f)[f])
,因此您正在执行对length(x)
值而不是nlevels(x)
值的数字转换。)
The speed difference will be most apparent for long vectors with few levels. (对于水平少的长矢量,速度差异最为明显。)
If the values are mostly unique, there won't be much difference in speed. (如果这些值大多是唯一的,则速度不会有太大差异。)
However you do the conversion, this operation is unlikely to be the bottleneck in your code, so don't worry too much about it. (无论您进行转换,此操作都不大可能成为代码中的瓶颈,因此不必担心太多。)
Some timings
(一些时机)
library(microbenchmark)
microbenchmark(
as.numeric(levels(f))[f],
as.numeric(levels(f)[f]),
as.numeric(as.character(f)),
paste0(x),
paste(x),
times = 1e5
)
## Unit: microseconds
## expr min lq mean median uq max neval
## as.numeric(levels(f))[f] 3.982 5.120 6.088624 5.405 5.974 1981.418 1e+05
## as.numeric(levels(f)[f]) 5.973 7.111 8.352032 7.396 8.250 4256.380 1e+05
## as.numeric(as.character(f)) 6.827 8.249 9.628264 8.534 9.671 1983.694 1e+05
## paste0(x) 7.964 9.387 11.026351 9.956 10.810 2911.257 1e+05
## paste(x) 7.965 9.387 11.127308 9.956 11.093 2419.458 1e+05
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…