[R] How to replace slashes with back slashes

Philippe Grosjean
2005-01-19T14:21:06Z

The second syntax is correct:

 > gsub('/', '\\\\', 'c:/dir1/dir2/file.ext')
[1] "c:\\dir1\\dir2\\file.ext"

Indeed, R escapes backslashes. That is why they are doubled in R
strings. However, they appear as single backslashes in oyur text file:

 > res <- gsub('/', '\\\\',
'c:/dir1/dir2/file.ext')
 > cat(res, file = "test.txt")
 > file.show("test.txt", delete.file = TRUE)

You got this in your file:

c:\dir1\dir2\file.ext

thus pretty readable by a Windows app.
Best,

Philippe Grosjean

..............................................<?}))><........
  ) ) ) ) )
( ( ( ( (    Prof. Philippe Grosjean
  ) ) ) ) )
( ( ( ( (    Numerical Ecology of Aquatic Systems
  ) ) ) ) )   Mons-Hainaut University, Pentagone (3D08)
( ( ( ( (    Academie Universitaire Wallonie-Bruxelles
  ) ) ) ) )   8, av du Champ de Mars, 7000 Mons, Belgium
( ( ( ( (
  ) ) ) ) )   phone: + 32.65.37.34.97, fax: + 32.65.37.30.54
( ( ( ( (    email: Philippe.Grosjean at umh.ac.be
  ) ) ) ) )
( ( ( ( (    web:   http://www.umh.ac.be/~econum
  ) ) ) ) )          http://www.sciviews.org
( ( ( ( (
..............................................................

Joerg Klausen wrote:
> Dear R-helpers
>
> I am running R2.0.0 under Windows 2000. I am compiling a number of file
paths into a simple text file that will be read by some other software we use.
Unfortunately, it  can only handle file paths with back slashes (MS Windows
convention), and from R, I get file paths with forward slashes. The following
didn't work.
>
>
>>gsub('/', '\\', 'c:/dir1/dir2/file.ext')
>
> [1] "c:dir1dir2file.ext"
>
>>gsub('/', '\\\\', 'c:/dir1/dir2/file.ext')
>
> [1] "c:\\dir1\\dir2\\file.ext"
>
> I have tried to find an answer on R-help, but didn't ;-(
>
> Thanks for helping me,
> Kind regards,
> J?rg
>
> Dr. J?rg Klausen                       phone : +41 (0)44 823 41 27
> EMPA (134)/GAW/QA-SAC     fax   : +41 (0)44 821 62 44
> ?berlandstrasse 129                 mailto: joerg.klausen at empa.ch
> CH-8600 D?bendorf                  http://www.empa.ch/gaw