Jason_K Jason_K - 1 year ago 74
R Question

Introducing NA to as.numeric

I have this string variable

mystr <- "98,015"

and I want to convert it to number.

So I use:

num <- as.numeric(mystr)

but I receive this error:

Warning message:
NAs introduced by coercion

This introduce NA instead the number. If a use a string like
I take the number successfully. What can I do?

Answer Source

We can use sub to replace the , with "" and then convert it to numeric. Because of the , character, applying the as.numeric coerces it to NA.

as.numeric(sub(",", "", mystr))

If , represent ., then replace it with . (Based on @RHertel's comments)

as.numeric(sub(",", ".", mystr))

It is not clear whether the OP's original dataset is a data.frame or just vector. If it is a data.frame, while reading with read.csv/read.table, we can specify the dec=",".