Getting a script's path in R
using this.path
Recently I found myself using R scripts from others and having to deploy my own R code on other machines. The majority of these had a hard coded path to either the script or the input data somewhere in the code. This becomes an issue when code needs to run on different machines, so here is a quick solution to this issue.
While I prefer Python over R, I do need to use R from time to time as some packages have no equivalent in Python (yet).
One issue with R I seem to be running into quite often is that depending on how you run a script, the working directory
may or may not be set to that script’s directory. Especially
those that like to open their .R files in RStudio without creating a proper project (like me) are likely to run into
issues where the working directory isn’t necessarily the folder the script is in. A quick-and-dirty solution is to
use setwd()
to set the working directory in the beginning of the script to your local folder. However, if that
script needs to be run by someone else on their machine, that path needs to be changed. The little snippet of code
below using the package this.path solves this issue. Though first make sure to install this package using install.packages("this.path")
.
Once this package is available, setting the working directory to the location of the script you are running is easily
achieved using the two lines of code below. Just for good measure we can verify the path is correct by adding print(getwd())
.
library(this.path)
setwd(this.dir())
Within that script you need to make sure to define all paths relative to the script’s location, and you are good to go on any system! At least what the paths to input, output and other code is concerned. To make sure all libraries are available on each system, and the versions match renv is needed. This is something I will dig into in a future post as it solves my other issues with R.
Liked this post ? You can buy me a coffee