2

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 "21" I take the number successfully. What can I do?

Jason_K
  • 43
  • 1
  • 5

2 Answers2

2

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=",".

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you. It works `as.numeric(sub(",", "", mystr))`! What should I do if I have a number like this "1,071,911" – Jason_K Sep 14 '16 at 13:56
  • 1
    @Jason_K In that case you can use `gsub` instead of `sub` (but from your example I thought there is only a single "," per each number – akrun Sep 14 '16 at 13:57
0

gsub function also does the same

mystr <- c("98,015","10,125","11,456")

mystr <- as.numeric(gsub("\\,","",mystr))

class(mystr)
 [1] "numeric"
Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22