问题
I need to change "/" into "\" in my R code. I have something like this:
tmp <- paste(getwd(),"tmp.xls",sep="/")
so my tmp
is c:/Study/tmp.xls
and I want it to be: c:\Study\tmp.xls
Is it possible to change it in R?
回答1:
Update as per comments.
If this is simply to save the file, then as @sgibb suggested, you are better off using file.path()
:
file.path(getwd(), "tmp.xls")
Update 2: You want double back-slashes.
tmp is a string
and if you want to have an actual backslash you need to escape it -- with a backslash.
However, when R
interprets the double slashes (for example, when looking for a file with the path indicated by the string), it will treat the seemingly double slashes as one.
Take a look at what happens when you output the string with cat()
cat("c:\\Study\\tmp.xls")
c:\Study\tmp.xls
The second slash has "disappeared"
Original Answer:
in R
, \
is an escape character, thus if you want to print it literally, you need to escape the escape character: \\
. This is what you want to put in your paste
statement.
You can also use .Platform$file.sep
as your sep argument, which will make your code much more portable.
tmp <- paste(getwd(),"tmp.xls",sep=.Platform$file.sep)
If you already have a string you would like to replace, you can use
gsub("/", "\\", tmp, fixed=TRUE)
来源:https://stackoverflow.com/questions/15645091/changing-into-in-r