1

I faced this issue for some numeric columns in R.Some of negative values in some columns are taken in brackets and column is convert into factor.

How to remove brackets in R and make value to negative? Eg. "(265)" to -265

How can I use gsub function in R to do this? If any other method is available, please suggest.

Pankaj Sharma
  • 388
  • 7
  • 18

2 Answers2

5

Here is an alternative. Regex match is made on values that start and end with a round bracket, and contain one or more numeric characters between, returning the middle-group (numeric characters) with a minus-sign in front. The whole lot is then cast to numeric:

as.numeric(gsub("^\\(([1-9]+)\\)$","-\\1",x))
Nicholas Hamilton
  • 10,044
  • 6
  • 57
  • 88
3

Just in case there is something else going on with numbers:

convert.brackets <- function(x){
  if(grepl("\\(.*\\)", x)){
    paste0("-", gsub("\\(|\\)", "", x))
  } else {
    x
  }
}

x <- c("123", "(456)", "789")

sapply(x, convert.brackets, USE.NAMES = F)

[1] "123"  "-456" "789" 

Otherwise simply:

paste0("-", gsub("\\(|\\)", "", x))
statespace
  • 1,644
  • 17
  • 25
  • Check out answers to related stack overflow question: **processing negative number in accounting format** [link](https://stackoverflow.com/questions/5068705/processing-negative-number-in-accounting-format) – adts Jul 23 '19 at 23:23