I have a script called foo.R
that includes another script other.R
, which is in the same directory:
#!/usr/bin/env Rscript
message(\
I just worked this out myself. To ensure portability of your script always begin it with:
wd <- setwd(".")
setwd(wd)
It works because "." translates like the Unix command $PWD. Assigning this string to a character object allows you to then insert that character object into setwd() and Presto your code will always run with its current directory as the working directory, no matter whose machine it is on or where in the file structure it is located. (Extra bonus: The wd object can be used with file.path() (ie. file.path(wd, "output_directory") to allow for the creation of a standard output directory regardless of the file path leading to your named directory. This does require you to make the new directory before referencing it this way but that, too, can be aided with the wd object.
Alternately, the following code performs the exact same thing:
wd <- getwd()
setwd(wd)
or, if you don't need the file path in an object you can simply:
setwd(".")