2

I have a vector I'm trying to convert from character to numeric. I've isolated it into the following. Any idea what is going on? Why is this 'number' or character sequence of '1,257.15' doing this? I'm uploading a data set of 8,000 rows and about 50 are producing an error when doing as.numeric() or as.numeric_version.

as.numeric(as.character('1,257.15'))
[1] NA
Warning message:
NAs introduced by coercion

traceback()
3: stop(gettextf("invalid version specification %s", paste(sQuote(unique(x[!ok])), 
       collapse = ", ")), call. = FALSE, domain = NA)
2: .make_numeric_version(x, strict, .standard_regexps()$valid_numeric_version)
1: numeric_version(as.character("1,256.15"))

numeric_version(as.character('1,256.15'))
Error: invalid version specification ‘1,256.15’

Then I tried this.

numericDeriv(as.character('1,257.15'))

Error in rep_len(dir, length(theta)) : 
  argument "theta" is missing, with no default
Tom
  • 53
  • 1
  • 6

1 Answers1

0

Remove the comma.

gsub(',', '', your_string_here)

Then, it will parse correctly.

a <- '1,257.15'
b <- gsub(',', '', a)
as.numeric(b)
CinchBlue
  • 6,046
  • 1
  • 27
  • 58
  • 1
    This is not robust for numbers with more than one comma, e.g. `1,234,567.89`. Just remove all commas like one of the other answers. – mathematical.coffee Aug 19 '15 at 01:40
  • @mathematical.coffee Done. – CinchBlue Aug 19 '15 at 01:41
  • Thank you. In my example, I typed out the string and did not have an extra space. While I like the solution, it bothers me that the solution is even needed. Any idea what is going on 'under the hood'? – Tom Aug 19 '15 at 12:13
  • Also, in using gsub(), the comma ( , ) seems to not be recognized. I cannot get the following code to work. gsub(',',"",SSB.Aug10$Quantity,fixed = T) – Tom Aug 19 '15 at 12:35