本文重点解决as.numeric()函数将factor转为数值时得出的无意义结果的解决
假设有数据框aaa
x | y | value
------------------------------------------
a1 b2 0.510665432157769
a2 b3 0.887655678543227
.. .. ...
运行as.numeric(aaa[1,3])
,返回的结果居然是123?当然,这只是个栗子,为了表达问题所在。真正运行时不一定得到的结果是123
在R help中找到如下参考
Warning
If x is a factor, as.numeric will return the underlying numeric (integer) representation, which is often meaningless as it may not correspond to the factor levels, see the ‘Warning’ section in factor (and the 2nd example below).
看到meaningless这个词了吗,意思是如果使用as.numeric转换一个因子,则通常会返回一个无意义的结果,是因子的一个“整型数字象征”,因为R为了节省内存提高速度,因子类型底层是用C语言中的int实现的,因子