有没有办法使用 tidyr 的 extract_numeric() 来提取负数?
例如,
> extract_numeric("2%")
[1] 2
> extract_numeric("-2%")
[1] 2
我真的很想第二次调用返回-2。
账单
PS:虽然我今天不关心,但我怀疑诸如“-$2.00”之类的情况会使任何一般解决方案复杂化。
extract_numeric
很简单:
> extract_numeric
function (x)
{
as.numeric(gsub("[^0-9.]+", "", as.character(x)))
}
<environment: namespace:tidyr>
它只是替换任何不是 0 到 9 或“。”的字符。一无所有。所以“-1”将变成 1,你对此无能为力......除了可能向 tidyr 提交增强请求,或者编写你自己的......
extract_num = function(x){as.numeric(gsub("[^0-9\\-]+","",as.character(x)))}
会做的:
> extract_num("-$1200")
[1] -1200
> extract_num("$-1200")
[1] -1200
> extract_num("1-1200")
[1] NA
Warning message:
In extract_num("1-1200") : NAs introduced by coercion
但是正则表达式可能会做得更好,只允许在开始时使用减号......
只需sub
在字符串中有一个数字时使用。这是一种方法:
功能:
myfun <- function(s) as.numeric(sub(".*?([-+]?\\d*\\.?\\d+).*", "\\1", s))
例子:
> myfun("-2%")
[1] -2
> myfun("abc 2.3 xyz")
[1] 2.3
> myfun("S+3.")
[1] 3
> myfun(".5PPP")
[1] 0.5