Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract numbers and operators from a given string

I have a vector like this:

 vec <- c("a + 17", "äÜ - 20*3")

There are different letters, numbers and operators. I want the get rid of the letters. Or, the other way around, to keep only the numbers and operators. Here is the result I am looking for:

 c("17", "-20*3")

I tried gsub("[:alpha:]", "", vec) but it doesn’t work and I don’t get why because [:alpha:] should remove any letters and then I should end up with the vector I am looking for. But this is not the case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I found a similar question but it didn’t help me either.

>Solution :

Here is a different approach using gsub:

x <- gsub("[^0-9+-/*]", "", vec)

c(as.numeric(x)[1], x[2])

output:

[1] "17"    "-20*3"
Warning message:
NAs introduced by coercion
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading