How to convert a factor variable to numeric while

2019-08-02 21:59发布

问题:

This question already has an answer here:

  • How to convert a factor to integer\numeric without loss of information? 7 answers

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.



标签: r merge r-factor