R is excellent for data transformation, modeling, etc. automatization. It is possible to run R scripts from the command line. In my case, I was collecting data and using library RDCOMClient to send summary information to colleges with Microsoft Outlook, but I needed it to do that automatically. It is possible to run R scripts with the help of the Windows command line and later run them automatically with Windows Task Scheduler, but there are a few things you should know.
There are two ways to run the R script from the Windows command line.
Use Rscript.exe. The first possible solution in the batch file looks like this.
"C:\Program Files\R\R-3.4.3\bin\Rscript.exe" C:\Users\myusername\Documents\R\Send_Outlook_Email.R
The second one with R.exe looks like this.
"C:\Program Files\R\R-3.4.3\bin\R.exe" CMD BATCH C:\Users\myusername\Documents\R\Send_Outlook_Email.R
Remember to use quotation marks when there is space in the file path.
Run R scripts from the command line
Here is how it goes step by step.
1. Find the path to R.exe or Rscript.exe on your computer. If you try to run R.exe from the command line, you enter into the R terminal.
In the Rscript.exe case, you can see additional usage options that might be useful. Try to stick to this one.
2. Find and copy the path to the R script file.
3. Open Notepad and combine two paths together (with quotation marks if needed and additional commands “CMD BATCH” if you choose to go with R.exe).
Using Rscript.exe is a convenient way.
"C:\Program Files\R\R-3.4.3\bin\Rscript.exe" C:\Users\myusername\Documents\R\Send_Outlook_Email.R
Here is with R.exe.
"C:\Program Files\R\R-3.4.3\bin\R.exe" CMD BATCH C:\Users\myusername\Documents\R\Send_Outlook_Email.R
4. Save as a file with extension .bat (for example send_email.bat).
5. Run that batch file to execute the R script.
If you want to schedule batch file execution on Windows, here is how to do that.
Related topics to running R scripts in batch mode
Look at this datacornering.com post if you want to add a progress bar in your R script and make it visible in non-interactive.
An alternative way to running an R script from the command line is using it as a source and executing from another R script. Another option if you are using Windows is to run the Windows batch file from the R script.
While the previously mentioned progress bar can also play sound during execution, here is another approach by using the Windows speech synthesizer.
Leave a Reply