Use forward-slashes instead.
On macos and linux, R uses forward-slashes only for directory separators. On windows, however, it accepts either, so all of the following will work on windows:
path <- "C:\\Users\\Me\\Desktop\\Data\\hotel_bookings.csv"
path <- "C:/Users/Me/Desktop/Data/hotel_bookings.csv"
# raw-strings, from Robby's answer
path <- r"{C:\Users\Me\Desktop\Data\hotel_bookings.csv}"
Personally I prefer using forward-slashes everywhere, first for cross-platform compatibility (backslashes don't work on non-windows platforms afaict), second because I've been in non-windows more than windows in my career so I'm more comfortable with forward-slashes.
Side note: I tend to agree that most of the time one should avoid absolute paths when working on projects. I'm assuming for this answer that there is (or can be) reason for using a full path. However, this answer is applicable to relative paths as well, such as
relpath <- "data\\hotel_bookings.csv"
relpath <- "data/hotel_bookings.csv"
relpath <- r"{data\hotel_bookings.csv}"
though clearly the number of slashes typed is far fewer.
On rereading the question a few more times, I see the utility of Rui's answer that suggests a programmatic way to change the text of what you're pasting. I'll add to that view a slightly different code-snippet that may be useful.
slashes <- function(txt) {
if (missing(txt)) txt <- clipr::read_clip()
clipr::write_clip(gsub("\\\\{1,2}", "/", txt))
}
# copy C:\\Users\\Me\\Desktop\\Data\\hotel_bookings.csv to your clipboard
slashes()
# you now have C:/Users/Me/Desktop/Data/hotel_bookings.csv
# in your clipboard, paste whereever
This is slightly different from Rui's in that it will replace single or up-to-double backslashes by a single forward slash.
file.path
would remove the need to type even a single \... and has the advantage of being robust to changes of operating system.normalizePath
in your code. Secondly, you should never hard-code paths to absolute files in your code, it makes the code unusable by others (and also by future you, if your folder structure changes). Either use relative paths, or make the path a parameter (as you’ve done viafile.choose()
, but this particular method has the substantial disadvantage of requiring user interaction when running the analysis).