[R] removing all non-numeric characters from a string, but not "."

Marc Schwartz marc_schwartz at me.com
Tue Jul 26 23:39:48 CEST 2016


> On Jul 26, 2016, at 4:28 PM, Dimitri Liakhovitski <dimitri.liakhovitski at gmail.com> wrote:
> 
> Hello!
> 
> I have a string x:
> x <- c("x - 84", "y - 293.04", "z = 12.5")
> 
> I want to remove all the non-numeric stuff from it. The following works:
> gsub("[^0-9]", "", x)
> 
> However, it strips my numbers of "."
> 
> Help - how could I do the same but leave the "." in?
> 
> Thanks a lot!
> 
> -- 
> Dimitri Liakhovitski


> gsub("[^0-9\\.]", "", x)
[1] "84"     "293.04" "12.5"  

The period needs to be escaped since it otherwise has special meaning in the regex.

Regards,

Marc Schwartz



More information about the R-help mailing list