Re: how to put a single backslash into a string, to make file paths usable on windows

Jeff Newmiller via R-help <[email protected]> Thu, 07 May 2026 08:00:54 -0700
Newsgroups gmane.comp.lang.r.general
Message-ID <[email protected]>
If you put the file paths in a data file in the script directory that you read in then the script doesn't need to concern itself with this detail... you can have a separate data file for each computer that you setup once.

paths.csv:
my_path_colname
C:\Users\MyID\Documents\Data

my_script.R:
my_path_DF <- read.csv( "paths.csv" )
my_path <- my_path_DF$my_path_colname

You can manipulate portions of paths using the file.path function.

my_file_path <- file.path( my_path, "my_data.csv" )

If you assume the directory "next" to your script has the data then simply moving the parent directory of your script directory can avoid the hardcoded absolute path: 

my_path <- "../data"

You can also embed windows file paths directly as strings using the r"()" string literal syntax that does not use \ as an escape character:

if ( "windows" == .Platform$OS.type ) {
  my_path <- r"(C:\Users\MyID\Documents\Data)"
} else {
  my_path <- "/home/myid/data"
}

though the data file is a cleaner approach.

If your client's computer environment can be configured (non-technical people may find this configuration method too obscure), then you can store the path in an environment variable using whatever mechanism is appropriate for that OS (e.g. .bashrc for Linux or the user environment variable control panel on Windows): 

per-user-environment:
MY_SCRIPT_DATA=C:\Users\MyID\Documents\Data

my_path <- Sys.getenv("MY_SCRIPT_DATA")


On May 7, 2026 6:18:09 AM PDT, Chris Ryan <[email protected]> wrote:
>It had been about a year since I had worked in Windows, and apparently I
>had gotten rusty. Forward slashes in path names, as in
>
>read.csv("e:/path/to/datafileOnWindows.csv")
>
>work just fine in R on Windows.
>
>Sorry for the bother.
>
>--Chris Ryan
>
>
>
>Chris Ryan wrote:
>> I'm trying to generalize one of my scripts so that it will run on my
>> Linux Mint computer at home and my client's Windows 11 computer at work.
>>  I'm encountering trouble when setting file paths, conditional on which
>> computer the script is running on. It's the Windows backslash issue
>>
>
>______________________________________________
>[email protected] mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

--
Sent from my phone. Please excuse my brevity.
	[[alternative HTML version deleted]]