Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 你能处理负数吗?_R_Tidyr - Fatal编程技术网

R 你能处理负数吗?

R 你能处理负数吗?,r,tidyr,R,Tidyr,有没有办法使用tidyr的extract_numeric()提取负数 比如说, > extract_numeric("2%") [1] 2 > extract_numeric("-2%") [1] 2 我真的希望第二个电话能返回-2 账单 PS:虽然我今天不关心这个问题,但我怀疑“-$2.00”这样的案例会使任何通用解决方案变得复杂。extract\u numeric非常简单: > extract_numeric function (x) { as.numeric(

有没有办法使用tidyr的extract_numeric()提取负数

比如说,

> extract_numeric("2%")
[1] 2
> extract_numeric("-2%")
[1] 2
我真的希望第二个电话能返回-2

账单


PS:虽然我今天不关心这个问题,但我怀疑“-$2.00”这样的案例会使任何通用解决方案变得复杂。

extract\u numeric
非常简单:

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

> 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

但是regexp可能做得更好,只允许在开始处使用减号…

如果字符串中只有一个数字,只需使用
sub
。以下是一种方法:

职能:

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

我想这取决于是否要将结果作为表达式进行求值。在gsubbed字符串上使用
eval(parse())
将返回一个数字。正如Spacedman所说,他的和Sven的解决方案在许多情况下给出了相同的答案,因此选择一个答案在很大程度上是投币。我确实选择了这个,因为它似乎做了我需要的事情,并通过生成NA来标记不明显的情况。谢谢你能在tidyr上提交一个bug或pull请求吗?请在github上存档问题。请注意,在“1-2-1234”中,摘录数字、您的解决方案和我的解决方案都给出了不同的答案。你付钱,你选择…@Spacedman当然,我们的函数在这个例子中给出了不同的结果。正如我所说,我的是打算用于字符串与一个单一的数字。
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