Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert anything that's not a number to blank

Tags:

regex

r

I have a vector of data, a similified version is below:

x <- c("1234123xcv?","12341534xxx.","hello","goodbye")

What I would like to do is have it return the following:

"1234123" "12341534" "" ""

I know I can do something like this, where I manually specify each upper/lower case letters and the few special characters that I'm aware of:

grep("[A-Za-z\\?\\.]",x,value=TRUE)

But I don't know what "else" is in the field that's not necessarily a number. (and can't look through it manually, because it's too large)

With that in mind my question is: Is there a way to specify that you want ONLY numbers to be returned in gsub()?

like image 847
Brandon Bertelsen Avatar asked Dec 22 '12 22:12

Brandon Bertelsen


2 Answers

gsub("\\D","",x) # yada yada yada
like image 92
flodel Avatar answered Oct 26 '22 18:10

flodel


Inside the brackets, ^ means not. So, this says replace whatever is not a number with ""

> gsub("[^0-9]", "", x)
[1] "1234123"  "12341534" ""         "" 
like image 43
GSee Avatar answered Oct 26 '22 18:10

GSee