I work with R on both Mac OS and Windows. On Windows, you get the option to copy the path of a file or folder by holding Shift while right-clicking on the file or folder. As useful as this feature is, it copies paths to your clipboard in Windows format, e.g. "C:\Users\someone\Documents\R\scripts\someproject\preparations.R"
That is not very nice to use in R scripts because you would have to replace every single backslash by a slash or a double backslash to use it. In this (also in other ways) very useful post, I found a nice solution for this.
By putting a function definition into your startup file (e.g., .Rprofile), you can simply put
.repath()
into the R console, paste your path and hit Return twice. The "de-windowsified" path is then in your clipboard. Here is the function definition:
.repath <- function() {
cat('Paste windows file path and hit RETURN twice')
x <- scan(what = "")
xa <- gsub('\\\\', '/', x)
writeClipboard(paste(xa, collapse=" "))
cat('Here\'s your de-windowsified path. (It\'s also on the clipboard.)\n', xa, '\n')
}
One nice thing about this (you R experts may of course know this) is that the function does not show up in RStudio's Environment section, because it is hidden by the dot before the name.
Thanks, Tom for this answer.
4
You're welcome! I'm glad you found it useful.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteIt sounds interesting but I cannot replicate this. It doesn't work in Rstudio or R.
ReplyDelete> "C:\Temp\Generated Data\data1.txt"
>
>
This does nothing.
The error is:
Error: '\T' is an unrecognized escape in character string starting ""C:\T"
Hey Bilge Adam, thanks for your comment.
ReplyDeleteI may not simply input your path at the R prompt. You have to type
> .repath()
first. Then paste your copied path into the prompt that appears. Then type Return twice. The clipboard then holds the corrected path.