as.numeric with comma decimal separators?

Fhnuzoag picture Fhnuzoag · Mar 6, 2013 · Viewed 48k times · Source

I have a large vector of strings of the form:

Input = c("1,223", "12,232", "23,0")

etc. That's to say, decimals separated by commas, instead of periods. I want to convert this vector into a numeric vector. Unfortunately, as.numeric(Input) just outputs NA.

My first instinct would be to go to strsplit, but it seems to me that this will likely be very slow. Does anyone have any idea of a faster option?

There's an existing question that suggests read.csv2, but the strings in question are not directly read in that way.

Answer

adibender picture adibender · Mar 6, 2013
as.numeric(sub(",", ".", Input, fixed = TRUE))

should work.