Pankaj Sharma
Pankaj Sharma

Reputation: 388

Removing Bracket in R and convert value to negative

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.

Upvotes: 1

Views: 3094

Answers (2)

Nicholas Hamilton
Nicholas Hamilton

Reputation: 10506

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))

Upvotes: 5

statespace
statespace

Reputation: 1664

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))

Upvotes: 3

Related Questions