1

($317.40)またはのように見える Excel の「会計」スタイルでフォーマットされたデータがあります$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))

これを1行で実行できますか?それができる専用の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 に答える