Convert to numeric: simplify 2 gsub calls to one

I would like to convert an alphanumeric vector to a numeric vector. Right now I'm using regex, but with 2 calls 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"

How can I simplify this for a single call using a unique regular expression or any other method? Thanks in advance.

+4
source share
1 answer

You will need to use cascading calls to create various notes if you use the R base.

However, you can use the gsubfn package , simplifying it using a list of notes.

library(gsubfn)

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

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

All Articles