[R] replacing period with a space

Sarah Goslee sarah.goslee at gmail.com
Tue Oct 13 19:37:07 CEST 2009


As you've discovered, the . means something special in regular
expressions (and R's version of them). You need to escape it with \\:

> x<-data.frame(x=c("aa.bb","cc.dd.ee"))
> x$x<-as.character(x$x)
> x
         x
1    aa.bb
2 cc.dd.ee
> sub("\\.", " ", x$x)
[1] "aa bb"    "cc dd.ee"
> gsub("\\.", " ", x$x)
[1] "aa bb"    "cc dd ee"

And to change all, you need gsub() rather than sub().

Sarah

On Tue, Oct 13, 2009 at 1:26 PM, Dimitri Liakhovitski <ld7631 at gmail.com> wrote:
> Dear R-ers!
>
> I have x as a variable in a data frame x.
>
> x<-data.frame(x=c("aa.bb","cc.dd.ee"))
> x$x<-as.character(x$x)
> x
>
> I am sorry for such a simple question - but how can I replace all
> periods in x$x with spaces?
>
> sub('.', ' ', x$x) - removes all letters to the left of each period...
>
> Thanks a lot for your advice!
>



-- 
Sarah Goslee
http://www.functionaldiversity.org




More information about the R-help mailing list