How to convert a factor variable to numeric while preserving the numbers in R [duplicate]

霸气de小男生 提交于 2019-12-11 05:13:01

问题


I wanted to merge to dataset by a variable ICPSR, but since the ICPSR was factor I had to change it to numeric variable. So I did as.numeric and after doing that, my ICPSR has been changed to a totally different values. I googled and found I need to use as.numeric(level(dv$ICPSR)). But it only turns out unique values not every value. So I was wondering how can I preserve every value and change it to merge-able numeric values.

Thanks in advance!

      ICPSR session   dv
 1:1  15245      103 0.75
 1:2  13003      103 0.00
 1:3  14620      103 0.25
 1:4  29105      103 0.00
 1:5  29104      103 0.00
 1:6  14414      103 0.25

 dv$ICPSR<-as.numeric(dv$ICPSR)
 head(dv)

      ICPSR session   dv
 1:1   202     103 0.75
 1:2    27     103 0.00
 1:3    85     103 0.25
 1:4   281     103 0.00
 1:5   280     103 0.00
 1:6    68     103 0.25

回答1:


dv$ICPSR <- as.numeric(as.character(dv$ICPSR))

Transform your factor to a character vector before transforming it into a numeric vector.



来源:https://stackoverflow.com/questions/20538084/how-to-convert-a-factor-variable-to-numeric-while-preserving-the-numbers-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!