[R] pasting "\" into character strings

John Miyamoto jmiyamot at u.washington.edu
Sun Dec 22 14:59:02 CET 2002


Thank you, Professor Ripley,
    Your comment does indeed lead to the solution to my problem as stated.
As you point out, this code

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

produces the output I want.  I need only indicate the file and append
option to achieve my purpose.

> x <- paste("c:",  "work", "part1.txt", sep="\\")
> cat(x, file = "out.txt", append = TRUE, "\n")

I discovered from this interchange that I did not quite state my problem
correctly, but the discussion solved the real problem as well as the
stated problem.  What started me on these questions was the desire to
write a function that would convert a R-intelligible file reference, e.g.,
'c:/work/part1.txt' to a Windows file reference, e.g.,
'c:\work\part1.txt'.  Having gotten this big hint, I now see how to solve
the problem as shown in the following:

> outfile <- "e:/temp/tmout1"
> outfile
[1] "e:/temp/tmout1"

> out.1 <- strsplit(outfile, "/")[[1]]
> out.1
[1] "e:"     "temp"   "tmout1"

> out.2 <- paste(out.1, sep="", collapse="\\")
> out.2
[1] "e:\\temp\\tmout1"

> cat(out.3, "\n")
e:\temp\tmout1

Since out.1 is a character vector, I needed to use 'collapse' rather than
'sep' to create "e:\\temp\\tmout1", but with this minor alteration,
everything works fine.

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/
--------------------------------------------------------------------




More information about the R-help mailing list