1

我有一个格式为 Excel 中“会计”样式的数据,看起来像($317.40)$13,645.48. 作为一个正则表达式新手,我正在寻找一种更有效的方法来删除所有无用的符号并将带括号的字符串转换为负数。

到目前为止,我是这样做的:

spending$Amount <- gsub("^[(]", "-", spending$Amount)
spending$Amount <- gsub("[$]", "", spending$Amount)
spending$Amount <- gsub("[)]", "", spending$Amount)
spending$Amount <- as.numeric(gsub("[,]", "", spending$Amount))

我可以在一行中做到这一点吗?是否有专门的 R 包可以做到这一点?

4

1 回答 1

2

嵌套gsub解决方案

x <- c("($317.40)", "$13,645.48")
as.numeric(gsub("\\(", "-", gsub("\\)|\\$|,", "", x)))
## [1]  -317.40 13645.48


## Really convoluted bad way of doing it solution 
mapply(FUN = function(x,y) ifelse(x,-1,1)*as.numeric(paste(y,collapse="")), grepl('\\(',x) ,regmatches(x, gregexpr('[0-9\\.]+',x)) )
于 2013-03-22T03:19:40.483 回答