Reputation: 27
I have a data frame, lets call is bob. bob has a column called "Rate" where the factor levels are a bunch of numeric values. I want to take the value in parenthesis and replace it with their negative values. For example: (50.00) now replace it with -50.00. There are several values within the column that are in parenthesis but I'm trying to find an efficient way. I have tried group<-(levels(bob$Rate))
" gsub(\\(|\\)", "-", group) But this changes (50.00) to -50.00- and I tried
gsub("\\(", "-", group) replaces ( with -
gsub("\\)", "", group) replaces ) with "" but it can only do one or the other not both.
Upvotes: 0
Views: 478
Reputation: 132969
Use a backreference:
gsub("(\\()(\\d+\\.?\\d*)(\\))",
"-\\2",
c("2.1", "20", "(50)", "(7.1)"), perl = TRUE)
#[1] "2.1" "20" "-50" "-7.1"
Upvotes: 2