Have windows task scheduler respect working directory set by .Rproj?

We develop our R work wherever possible using .RProj, and when opening the file in RStudio using it's lovely features to set the working directory behind the scenes. This is useful for our team as it helps with portability and shareability, and works nicely with git.

However, we also have a requirement to use Windows Task Scheduler sometimes to execute an R script. The script is in a project, and relies on accessing some folders which are the children of the working directory. Right now there is a line at the top of the script setwd(C:/Reports/Report_A).

This is because when the script is called by Windows Task Scheduler, it is called in the form:

Action:
  Start Program: "C:\Program Files\R\R-3.3.1\bin\Rscript.exe"
    Add arguments (optional): "C:\Reports\Report_A\run_this_daily.R"

Because the script itself is called from the r installation, the project is not hit in the automated deployment, so the working directory isn't set. The (small) frustration is that the setwd() is relatively bad practice, and can lead to simple errors/novice users confusion.

Is there any experiences? Is there a different setting to supply to the Start Program? Or maybe this should be handled in the script with a config file? Or should the script check the working directory that is currently set and change it only if the working directory is not named the same as the report?

Local-directory stuff can be a massive pain in Windows, but I love that you are going that direction. It does work so nicely with git and makes for a solid step towards portable / reproducible code.

I definitely agree that setwd is not the right way to go, because then if you move the directory (i.e. git clone or something like it), you end up in trouble. It's really nice to only be concerned about child folders (and not having to worry about parents). There are a bunch of possible ways to work around this issue. config file is an option (check out the config package!).

Honestly, though, I think the rprojroot package was designed with exactly this case in mind, so I would suggest checking it out! The here package is related.

One final tidbit. Although I have since cut ties with Windows and (hopefully) the nightmares of the Task Scheduler, I recall setting the project directory in the Task Scheduler as well (This was before the rprojroot package). There are a handful of ways to do this, but a screenshot (and other answers with more info) is available here:

3 Likes

This is fantastic! I am continually having my eyes opened by the community on this site :slight_smile:

1 Like

So glad that was helpful! :slight_smile: Me too! So much learning - so little time!