[R] pasting "\" into character strings

Henrik Bengtsson hb at maths.lth.se
Sun Dec 22 09:38:04 CET 2002


R is interpreting \" as the ASCII character for ", not "\". This means
that your second argument to paste() is the string "\", " and there
there follows a 'work', which is why you get a syntax error.

Yes, you should use \\ for backslash, e.g.

> pathname <- paste("c:", "\\", "work", "\\", "part1.txt", sep="")
> print(pathname)
[1] "c:\\work\\part1.txt"
> cat(pathname, "\n")
c:\work\part1.txt

Note that the "\\" is not two characters but one, i.e. nchar("\\") == 1.

Henrik Bengtsson


> -----Original Message-----
> From: r-help-admin at stat.math.ethz.ch 
> [mailto:r-help-admin at stat.math.ethz.ch] On Behalf Of John Miyamoto
> Sent: den 22 december 2002 19:01
> To: R discussion group
> Subject: [R] pasting "\" into character strings
> 
> 
> Dear R-Help,
>    I'm using R version 1.6.0 on a Windows computer.  I am 
> trying to create a function that, among other things, 
> constructs strings that refer to Windows files, e.g., I might 
> want to construct a string like 'c:\work\part1.txt'.  I have 
> found that the following does not work.
> 
> > paste("c:", "\", "work", "\", "part1.txt", sep="")
> Error: syntax error
> 
> I'm guessing that R interprets "\" as some kind of special 
> control character, and that there is some way to show that 
> one wants a literal interpretation of "\" and not a control 
> interpretation, but I haven't been able to find an 
> explanation of this issue.  I understand that I must use 
> 'c:\\work\\part1.txt' or 'c:/work/part1.txt' to refer to the 
> file that Windows knows as 'c:\work\part.txt', but what I'm 
> trying to do is to write an R function that writes references 
> to Windows files into a text file, where a different Windows 
> programs will later read these references in the standard 
> Windows syntax.
>    Can someone tell me how to create the character string 
> 'c:\work\part1.txt' from the parts, "c:", "work", an "part1.txt"?
> 
> John Miyamoto
> 
> --------------------------------------------------------------------
> John Miyamoto, Dept. of Psychology, Box 351525
> University of Washington, Seattle, WA 98195-1525
> Phone 206-543-0805, Fax 206-685-3157, Email 
> jmiyamot at u.washington.edu Homepage 
> http://faculty.washington.edu/jmiyamot/
> 
> --------------------------------------------------------------------
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list 
> http://www.stat.math.ethz.ch/mailman/listinfo/> r-help
> 
>




More information about the R-help mailing list