Converting dot to comma in numeric

Manuel Frias picture Manuel Frias · Nov 26, 2014 · Viewed 27.3k times · Source

If I have a data frame:

a   b  
2.4 4.6
3.6 66.7
5.8 44.6

Both a and b are numeric.

I want to convert "." to "," with

df$a <- as.numeric(gsub(".", ",", df$a))

but I always get

Warning message:NAs introduced by coercion

and all values are converted to NA. Why?

Answer

romants picture romants · Nov 26, 2014

Your initial idea was almost correct, just regular expression was wrong, because . matches any symbol. You need something like (this will convert numeric vector to a character vector)

df$a <- gsub("\\.", ",", df$a)

Also you can change the output from R printing, plotting and the actions of the as.character function. You change it from its default with:

options(OutDec= ",")

And another option is using format function.

format(df, decimal.mark=",")

I assume that you care about how numbers are printed (output), because internally numeric is stored as a double precision floating point number (Update thanks to comment by @digemall). Also unless for some function like read.table it is specifically specified that decimal separator is ,, it's not possible to do otherwise, because by default , is used for separating function arguments.

And NA are introduced exactly for that reason (aside from incorrect regex).

df$a <- as.numeric(gsub("\\.", ",", df$a))

By default parser does not know that , is used as a decimal separator.