This is more an Rstudio tip than an R tip. It would be nice to know how the following works for different editors, but Rstudio is common enough and awesome enough for the following to be relevant.
In Rstudio you can set the default working directory using tools -> Global options -> General -> default working directory
. Do that, and next time you open Rstudio your working directory is what you specified there.
My working directory is dropbox, but I always have sub-folders from which I open different scripts.
You can use the following code to automate setting the working directory directly to that folder you open the script from. You can do this using the rstudioapi
package:
1 2 3 4 5 6 7 8 9 10 |
# install.packages("rstudioapi") # run this if it's your first time using it to install library(rstudioapi) # load it # the following line is for getting the path of your current open file current_path <- getActiveDocumentContext()$path # The next line set the working directory to the relevant one: setwd(dirname(current_path )) # you can make sure you are in the right directory print( getwd() ) |
So when you open a script, does not matter where from, run this to have Rstudio understand which directory you would like to work from.
Take it a step further, create your own setwd
function
1 2 3 4 5 6 7 8 |
set_wd <- function() { library(rstudioapi) # make sure you have it installed current_path <- getActiveDocumentContext()$path setwd(dirname(current_path )) print( getwd() ) } |
Now the function set_wd()
sets the working directory to the folder you are now working from. So we don’t need the clunkier setwd("paste here the absolute path")
.
Tech Tip : Now you can work on your code from anywhere with multiple devices using a windows based hosted virtual desktop. You can take a risk-free trial from a Desktop-as-a-Service provider(DaaS) such as CloudDesktopOnline.com. For SharePoint and Exchange hosting you can try Apps4Rent.com.