R - gsub only digits

giac picture giac · Oct 18, 2015 · Viewed 7.5k times · Source

I would like to clean this vector and only retain the digits

vec = c(" 4010  \"Filling in time budget diary\"", " 8888  \"Prob cont. preceding activity\"", " 9999   \"Missing, undecipherable\";") 

what I would like is simply : 4010, 8888, 9999

I thought of something like, matching exactly the digits but it doesn't work.

gsub("^[[:digit:]]$", replacement = '', vec)

Thanks

Answer

akrun picture akrun · Oct 18, 2015

We can use \\D+ to match all non-numeric elements and replace with ''

 gsub('\\D+','', vec)