How to convert a character vector to numeric?

Bruno Camarda picture Bruno Camarda · Jan 16, 2018 · Viewed 30.9k times · Source

I have this character vector but I need to convert this to numeric.

>iono_test_y
[1] "g" "b" "b" "g" "g" "g" "b" "g" "b" "b" "g" "b" "g" "b" "b" "b" "g" "g" "b" "b" "b" "g" "g"
[24] "b" "b" "g" "g" "g" "b" "g" "g" "g" "b" "b" "b" "b" "b" "g" "g" "g" "g" "g" "b" "g" "b" "b"
[47] "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g" "g"
[70] "g" "g"

I already tried

iono_test_y <- as.numeric(as.character(iono_test_y)

but it doesn't seem to work. How can I do that?

Answer

G5W picture G5W · Jan 16, 2018

It appears that your variable is just a character vector, not a factor. You can give it a numeric encoding by using

as.numeric(factor(iono_test_y))