如何在不丢失信息的状况下将因子转换为整数\\数字? - How to convert a factor to integer\numeric without loss of information?

问题:

When I convert a factor to a numeric or integer, I get the underlying level codes, not the values as numbers. 当我将因子转换为数字或整数时,我获得的是底层的级别代码,而不是数值。 spa

f <- factor(sample(runif(5), 20, replace = TRUE))
##  [1] 0.0248644019011408 0.0248644019011408 0.179684827337041 
##  [4] 0.0284090070053935 0.363644931698218  0.363644931698218 
##  [7] 0.179684827337041  0.249704354675487  0.249704354675487 
## [10] 0.0248644019011408 0.249704354675487  0.0284090070053935
## [13] 0.179684827337041  0.0248644019011408 0.179684827337041 
## [16] 0.363644931698218  0.249704354675487  0.363644931698218 
## [19] 0.179684827337041  0.0284090070053935
## 5 Levels: 0.0248644019011408 0.0284090070053935 ... 0.363644931698218

as.numeric(f)
##  [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2

as.integer(f)
##  [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2

I have to resort to paste to get the real values: 我必须求助于paste以得到真实的价值: .net

as.numeric(paste(f))
##  [1] 0.02486440 0.02486440 0.17968483 0.02840901 0.36364493 0.36364493
##  [7] 0.17968483 0.24970435 0.24970435 0.02486440 0.24970435 0.02840901
## [13] 0.17968483 0.02486440 0.17968483 0.36364493 0.24970435 0.36364493
## [19] 0.17968483 0.02840901

Is there a better way to convert a factor to numeric? 有没有更好的方法能够将因子转换为数值? code


解决方案:

参考一: https://stackoom.com/question/ELD6/如何在不丢失信息的状况下将因子转换为整数-数字
参考二: https://oldbug.net/q/ELD6/How-to-convert-a-factor-to-integer-numeric-without-loss-of-information
相关文章
相关标签/搜索