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

4.8k views Asked by At

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

There are 1 answers

0
Sven Hohenstein On BEST ANSWER
dv$ICPSR <- as.numeric(as.character(dv$ICPSR))

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