agstudy
agstudy

Reputation: 121578

convert to numeric : simplify 2 calls of gsub to one

I would like to convert a vector of alphanumeric to numeric vector. Right now , I am using regex but with 2 calls to 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 to one call, using unique regex or any other method? Thanks in advance.

Upvotes: 4

Views: 129

Answers (1)

hwnd
hwnd

Reputation: 70732

You'll need to use cascading calls to make the different replacements if using base R.

However, you can utilize the gsubfn package, simplifying it using a replacement list.

library(gsubfn)

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

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

Upvotes: 1

Related Questions