Set working directory of your R script automatically

When you’re working with some datasets in R-studio, you have to define an absolute path to such file and set the working directory of your script accordingly. Doing this would be very time-consuming in some occasions. Luckily, there’s an API call that can simplify the process.

setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

It is best that  you place the R-script and the datasets in the same folder. Make sure to include the given command at the top of your script for the best portability. If your collaborators want to run the R-script on their computer, they wouldn’t have to change the working directory themselves, how cool is that!

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.