Re: [R] Replacing backslashes with slashes

From: Prof Brian Ripley <>
Date: Thu 05 Jan 2006 - 01:08:06 EST

On Wed, 4 Jan 2006, yvonnick noel wrote:

> Hello,
> I've seen this question asked in the archives but no clear reply or solution
> provided.

I've seen the answer many times: what were you searching on?

> So, just to be sure it is not possible in R: Can I replace
> backslashes with slashes in a string ?

Yes. The Windows R code does it in several places.

> I am writing a GUI for R with the Rpad library. I have a "browse" button for
> data loading and Windows return a path string with backslashes. I need to
> convert them into slashes to use the string with read.table.

Actually, read.table accepts any valid file path, so I don't see why.

> I would have expected something like:
> gsub("\\","\/","c:\My Documents\data.dat")
> to work but it does not (incorrect regular expression).

You need one of

gsub("\\\\","/","c:\\My Documents\\data.dat")
gsub("\\","/","c:\\My Documents\\data.dat", fixed = TRUE)
chartr("\\", "/", "c:\\My Documents\\data.dat")

Note that you need to be careful in certain multi-byte locales to change characters not bytes, but nowadays (post 2.1.0) R is careful.

> Note that I have no control on the string which is returned from the
> system (no such problem under Linux BTW).

Really? What happens with file names containing backslashes on Linux?

The string will have embedded backslashes, represented by \\ in quoted strings in R ...

> Any idea ?
> Yvonnick NOEL
> U. of Rennes 2

Brian D. Ripley,        
Professor of Applied Statistics,
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________ mailing list
PLEASE do read the posting guide!
Received on Thu Jan 05 01:15:50 2006

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:41:48 EST