Handling bracketed negatives in readr

81 views Asked by At

read_csv's col_number doesn't handle bracket-style negatives. This solution works, but I'm curious to know if there is a simpler one?

library(tidyverse)
library(stringr)
data <- read_csv2("num\n12\n(12)\n13\n£2,250.00")
data$num <- data$num %>% 
  str_replace("^\\(([1-9]+)\\)$","-\\1") %>% 
  parse_number()
head(data)

# A tibble: 4 x 1
    num
  <dbl>
1    12
2   -12
3    13
4  2250
0

There are 0 answers