[英]Regex issue in R with gsub - reformat string vector to numeric
I am trying to take a character vector of dollar values that is poorly formatted and turn it into a numeric. 我试图采用格式不佳的美元值的字符向量并将其转换为数字。 The values are formatted as in the following vector, with a leading and trailing space, a comma, and a dollar sign:
值的格式如下所示,带有前导和尾随空格,逗号和美元符号:
x <- c(" 18,000.50 ", " $1,240.30 ", " $125.00 ")
I am trying to use the following function to get rid of all characters other than the digits and the dot, but it isn't working: 我试图使用以下函数来摆脱除数字和点之外的所有字符,但它不起作用:
trim_currency <- function(x) grep("\$([0-9.]*)\,([0-9.]*)", x, values=TRUE)
I got the regex code 我得到了正则表达式代码
\$([0-9.]*)\,([0-9.]*)
to run successfully with this regex tester http://regex101.com/r/qM2uG0 使用此正则表达式测试程序http://regex101.com/r/qM2uG0成功运行
When I run it in R, I get the following error: 当我在R中运行它时,我收到以下错误:
Error: '\$' is an unrecognized escape in character string starting "\$"
Any ideas about how I can do this in R? 关于如何在R中做到这一点的任何想法?
Thanks to ndoogan for his response. 感谢ndoogan的回应。 That solves this particular issue.
这解决了这个特殊问题。 However, if I wanted to make it more general, I would ask:
但是,如果我想让它更通用,我会问:
How could I use R/regex to run a vector through a filter, allowing only the digits and periods to come through? 我如何使用R / regex通过过滤器运行向量,只允许数字和句点通过?
x <- c(" 18,000.50 ", " $1,240.30 ", " $125.00 ")
gsub("[,$ ]","",x)
#[1] "18000.50" "1240.30" "125.00"
Add more characters within the brackets to eliminate different things. 在括号内添加更多字符以消除不同的内容。 I assume the example
x
is exhaustive here. 我假设示例
x
在这里是详尽无遗的。
Update 更新
If you know you're only interested in numeric digits and decimal points, then you could do this: 如果您知道自己只对数字和小数点感兴趣,那么您可以这样做:
gsub("[^0-9.]","",x)
#[1] "18000.50" "1240.30" "125.00"
The ^
inside the square brackets negates the meaning of the statement in square brackets. 方括号内的
^
否定了方括号中语句的含义。
Finally, to get resulting values into numeric form, wrap the gsub()
function (or an object containing its output) in as.numeric()
: 最后,要将结果值转换为数字形式,请将
gsub()
函数(或包含其输出的对象gsub()
包装在as.numeric()
:
as.numeric(gsub("[^0-9.]","",x))
#[1] 18000.5 1240.3 125.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.