简体   繁体   中英

Can extract_numeric deal with negative numbers?

Is there a way to use tidyr's extract_numeric() to extract negative numbers?

For example,

> extract_numeric("2%")
[1] 2
> extract_numeric("-2%")
[1] 2

I'd really like the second call to return -2.

Bill

PS: While it doesn't concern me today, I suspect cases such as "-$2.00" complicate any general solution.

extract_numeric is pretty simple:

> extract_numeric
function (x) 
{
    as.numeric(gsub("[^0-9.]+", "", as.character(x)))
}
<environment: namespace:tidyr>

It just replaces any char that isn't 0 to 9 or "." with nothing. So "-1" will become 1, and there's nothing you can do about it... except maybe file an enhancement request to tidyr, or write your own...

extract_num = function(x){as.numeric(gsub("[^0-9\\-]+","",as.character(x)))}

will sort of do it:

> 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

but a regexp could probably do better, only allowing minus signs at the start...

Just use sub if there's a single number in the string. Here's an approach:

The function:

myfun <- function(s) as.numeric(sub(".*?([-+]?\\d*\\.?\\d+).*", "\\1", s))

Examples:

> myfun("-2%")
[1] -2
> myfun("abc 2.3 xyz")
[1] 2.3
> myfun("S+3.")
[1] 3
> myfun(".5PPP")
[1] 0.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM