Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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
Regex 转换为数字:将gsub的2个调用简化为1个_Regex_R - Fatal编程技术网

Regex 转换为数字:将gsub的2个调用简化为1个

Regex 转换为数字:将gsub的2个调用简化为1个,regex,r,Regex,R,我想把字母数字向量转换成数字向量。现在,我正在使用regex,但有2个对gsub的调用: ## wrapping this in function to_numeric <- function(x) gsub(',','.',gsub("[^(\\d|,)]","",x,perl=TRUE)) ## call it to_numeric(c('a12,12','Atr 145 ',' 14 5,1 4A')) ## [1] "12.12" "145" "145.14"

我想把字母数字向量转换成数字向量。现在,我正在使用regex,但有2个对gsub的调用:

## wrapping this in function 
to_numeric <-
  function(x)    gsub(',','.',gsub("[^(\\d|,)]","",x,perl=TRUE))
## call it 
to_numeric(c('a12,12','Atr 145 ',' 14 5,1 4A'))
## [1] "12.12"  "145"    "145.14"
##将其包装到函数中

如果使用base R,则需要使用级联调用来进行不同的替换

但是,您可以利用该包,使用替换列表简化它

library(gsubfn)

x <- c('a12,12', 'Atr 145 ', ' 14 5,1 4A')

gsubfn('\\D+', list(',' = '.', ''), x)
# [1] "12.12"  "145"    "145.14"
库(gsubfn)

x您需要使用两个函数。
[^(\\d |,)]
不过这看起来有点可疑。是否仅排除
\d
?或者你想把
()|
也排除在外吗?你不需要使用两个函数,除非你能指望数字是连续的,否则它既不美观也不高效…@agstudy:我想你可以从qdap中使用
mgsub
,类似这样的:
库(qdap)//查找