Search code examples
rreadr

How do I convert a negative dollar value surrounded by parenthese to numeric?


I have a df that has a column where the negative dollar values are surrounded by parentheses. How do I convert the column into numeric for both positive and negative values? parse_number works for positives, but doesn't account for parentheses representing negative values.

Sample DF

sample <- 
  tibble::tribble(
   ~id, ~dollars,
    36, "($0.3)",
  1890,   "$3.6",
  3298, "($0.1)",
  3448,   "$0.2",
  4616,   "$0.0",
  5409, "($0.1)",
  5751, "($0.1)",
  5942,   "$0.1",
  6316,   "$0.0",
  6589,   "$0.1"
  )

Solution

  • The following will do what the question asks for.

    as.numeric(sub("\\(", "-", gsub("\\)|\\$","", sample$dollars)))
    # [1] -0.3  3.6 -0.1  0.2  0.0 -0.1 -0.1  0.1  0.0  0.1
    

    Less readable but simpler, just one *sub.

    as.numeric(gsub("\\(*\\$([[:digit:].]+)\\)*", "-\\1", sample$dollars))
    # [1] -0.3  3.6 -0.1  0.2  0.0 -0.1 -0.1  0.1  0.0  0.1