Search code examples
rcurrencyreadr

Negative currency values using parse_number in readr R


I'm importing sales data that needs to be converted from character strings to numeric.

I'm trying to use parse_number in readr to do this, but it throws a parsing error for negative values, and coerces them to NAs.

As an example:

x <- c("$1,000.00", "$500.00", "-$200.00")

y <- parse_number(x)

Warning: 1 parsing failure. row # A tibble: 1 x 4 col row col expected actual expected <int> <int> <chr> <chr> actual 1 3 NA a number -

y

[1] 1000 500 NA

Does parse_number or readr have functionality that allows me to keep "-" for negative currency values?

(I'm not asking for an as.numeric(gsub()) solution.)


Solution

  • If you want to stay with tidyverse functions as per comment here you can just use stringr functions instead of gsub. Options like this:

    library(tidyverse)
    x <- c("$1,000.00", "$500.00", "-$200.00")
    x %>%
      str_replace("^-\\$(.*)$", "$-\\1") %>%
      parse_number()
    #> [1] 1000  500 -200
    
    x %>%
      str_remove("\\$") %>%
      parse_number()
    #> [1] 1000  500 -200
    

    Created on 2018-05-03 by the reprex package (v0.2.0).