Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - gsub only digits

Tags:

regex

r

gsub

grepl

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

like image 599
giac Avatar asked Dec 10 '22 20:12

giac


1 Answers

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

 gsub('\\D+','', vec)
like image 50
akrun Avatar answered Jan 02 '23 04:01

akrun