我有一个数据框,让我们打电话是bob。 bob有一个名为" Rate"因子水平是一堆数值。我想在括号中取值并用它们的负值替换它。例如:(50.00)现在将其替换为-50.00。列中的几个值在括号中,但我试图找到一种有效的方法。我试过了 基团LT ;-(水平(BOB $率))
" 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.
答案 0 :(得分:2)
使用反向引用:
gsub("(\\()(\\d+\\.?\\d*)(\\))",
"-\\2",
c("2.1", "20", "(50)", "(7.1)"), perl = TRUE)
#[1] "2.1" "20" "-50" "-7.1"