any way to schedule an R program to run daily? - r

I am using R program to collect and update data from some local and online sources, which are updated frequently.
Since these sources are fixed, there is no argument to pass to the program, and everything is routine.
Now my supervisor wants me to set this as a scheduled daily task. I know it is impossible for .r file. Is there any way to compile the r file to executable file? such as .exe, .bat, ... ...
I don't need the executable file to be standalone, I can keep R in my computer.
any suggestion is appreciated.

You need to use the standard OS facilities (cron/at on Unix) to run R with the appropriate argument.
E.g., if you add the functions you need to .Rprofile, you can do
R --no-save --no-restore -q -e 'MyFunc(my,args)'
Alternatively, you might want to use Batch Execution of R.

For Windows I have hundreds of scripts that are set up with bat files similar to the below. It assumes that you have a NameOfScript.bat and a NameOfScript.r in the same folder and then run the .bat file from Scheduler and it logs everything from stdout/err to NameOfScript_yyyy-mm-dd.log in the same folder. I normally have the log folder seperate but adding that can be done just by changing the definition of LOG_FILE. Also passes in the folder it's in to R just in case you need to output some files in the folder.
IF DEFINED ProgramFiles(x86) (
SET R_SCRIPT="%ProgramFiles(x86)%\\R\\R-2.15.2\\bin\\Rscript.exe"
) ELSE (
SET R_SCRIPT="%ProgramFiles%\\R\\R-2.15.2\\bin\\Rscript.exe"
)
IF NOT EXIST %R_SCRIPT% GOTO FAIL
SET SCRIPT_DIR=%~dp0
SET SCRIPT_DIR=%SCRIPT_DIR:\=\\%
SET BATCH_FILE=%0
SET BATCH_FILE=%BATCH_FILE:"=%
SET SCRIPT_TO_RUN="%BATCH_FILE:.bat=.r%"
SET day=%DATE:~0,2%
SET month=%DATE:~3,2%
SET year=%DATE:~6,4%
SET yyyymmdd=%year%-%month%-%day%
SET LOG_FILE="%BATCH_FILE:.bat=%"_%yyyymmdd%.log
SET SCRIPT_DIR="%SCRIPT_DIR%"
%R_SCRIPT% --internet2 --max-mem-size=2047M --no-restore --no-save --args %SCRIPT_DIR% < %SCRIPT_TO_RUN% >> %LOG_FILE% 2>&1
PAUSE
EXIT /B 0
:FAIL
ECHO RScript not found. Failed process

You could also call the R script from C#, and run the C# project as a scheduled task.

Related

Calling bash from within R

I have R generating some .csv files for another python program to run in another folder, I know it is possible to call bash from R but how could I call the command make in my ubuntu virtual machine in another directory?
The simple way is creating an script to cd to your dir and exec make after that
script <- tempfile()
fhandle <- file(script)
writeLines("( cd /your_directory && make )",con=fhandle)
system2("/bin/bash",args=c(script))
You may need to find the correct path to /bin/bash, mine is from MacOs
You can work with system2 parameters to control what happens with output from make command and if you want to run the process in parallel with your R task or wait for completion.

Running Rscript in Bash on Windows

I'm writing a Git hook which should run some R code. If the hook starts with
#!/usr/bin/env Rscript
then the following code is correctly interpreted as R.
However, Rscript looks for my installed packages in my home directory. According to the R for Windows FAQ, the home directory is defined by the environment variables R_USER or HOME. However, the Git Bash shell does not contain either of these, so the home directory defaults to the working directory.
The hook, therefore, fails to locate any non-base packages.
The solution I've found is to create an R file and then use Bash in the hook to call Rscript after manually defining R_USER:
#!/bin/sh
R_USER="my/home/directory"
export R_USER
Rscript foo.R
(Where foo.R is in the project's working directory, in this case).
This works but is somewhat inelegant. I'd rather simply use Rscript in the hook itself.
So I considered setting the home directory within the Rscript:
#!/usr/bin/env Rscript
Sys.setenv(R_USER = "my/home/directory")
But while that does set R_USER, it doesn't fix the problem. I assume this means that R defines the package-finding path before the script itself is run, so defining R_USER within the script doesn't change the fact that it's still looking for packages in the working directory instead.
So, is there a solution to this (for example, by setting R_USER and then somehow telling R to update the package directory)? Or is the use-Bash-to-call-Rscript method the way to go?

Unable to run R script through .bat files in Windows Server

I'm trying to run a R script through a .bat file. When I run myself the commands line by line it works. But when I try to run the .bat file, it doesn't works.
This is the .bat file
cd "C:\Program Files\R\R-3.1.2\bin"
R CMD BATCH "C:\Users\Administrator\Downloads\testa_vps.R"
This is the R script
setwd('C:\Users\Administrator\Documents')
file.create('mycsv.csv')
I'm not an expert with Windows and generally try to stick to Unix-like systems for things like this, but I have found that using programs non-interactively (e.g. via .bat files) is usually less error-prone when you add the appropriate directories to your (user) PATH variable, rather than cding into the directory and calling the executable from within the .bat file. For example, among other things, my user PATH variable contains C:\PROGRA~1\R\R-3.0\bin\; - the directory that contains both R.exe and Rscript.exe - (where PROGRA~1 is an alias for Program Files which you can use in an unquoted file path, since there are no spaces in the name).
After you do this, you can check that your PATH modification was successful by typing Rscript in a new Command Prompt - it should print out usage information for Rscript rather than the typical xxx is not recognized as an internal or external command... error message.
In the directory C:\Users\russe_000\Desktop\Tempfiles, I created test_r_script.r, which contains
library(methods)
setwd("C:\Users\russe_000\Desktop\Tempfiles")
file.create("mycsv.csv")
and test_r.bat, which contains
Rscript --vanilla --no-save "C:\Users\russe_000\Desktop\Tempfiles\test_r_script.r"
Clicking on the Windows Batch File test_r ran the process successfully and produced mycsv.csv in the correct folder.
Before running test_r.bat:
After running test_r.bat:
I've never worked with a Windows server, but I don't see why the process would be fundamentally different than on a personal computer; you just may need your sysadmin to modify the PATH variable if you don't have sufficient privileges to alter environment variables.
As already suggested by #nrussel in the comments you should use RScript.exe for this.
Create a file launcher.bat with the following content:
cd C:\Users\Administrator\Documents
Rscript testa_vps.R
In addition, add C:\Program Files\R\R-[your R version]\bin\x64; or C:\Program Files\R\R-[your R version]\bin\i386to the System PATH variable in the Environment Variables menu depending if you run R on a 64-bit or 32-bit system.
I just tested the approach above successfully on a Windows Server 2008 64-bit system and mycsv.csv got created as expected.
EDIT
One important point I forgot to mention is the following: You need to specify the path in your R file in the setwd() call using \\ instead of \.
setwd('C:\\Users\\Administrator\\Documents')
Here is a screenshot of the successful run on the Windows 2008 server:
Note: I added cmd /k to the .bat file so that the cmd window stays open after clicking on the file.

batch process for R gui

I have created a batch file to launch R scripts in Rterm.exe. This works well for regular weekly tasks. The < PBWeeklyMeetingScriptV3.R > is the R script run by Rterm.
set R_TERM="C:\Program Files\R\R-2.14.0\bin\x64\Rterm.exe"
%R_TERM% --slave --no-restore --no-save --args 20120401 20110403 01-apr-12 03-apr-11 < PBWeeklyMeetingScriptV3.R > PBWeeklyMeetingScriptV3.batch 2> error.txt
I've tried to modify this to launch the R GUI instead of the background process as I'd like to inspect and potentially manipulate and inspect the data.
If I change my batch file to:
set R_TERM="C:\Program Files\R\R-2.14.0\bin\x64\Rgui.exe"
the batch file will launch the R GUI but doesn't start the script. Is there a way to launch the script too?
Alternatively is there a way to save/load the work space image to access the variables that are created in the script?
You can save and load workspaces by using save.image() and load(). I do this all the time when scripting to pass data sets between two separate script files, tied together using Python or bash. At the end of each R script, just add:
save.image("Your_image_name.RData")
The image will be the workspace that existed whenever the command was run (so, if it's the last command in the file, it's the workspace right before the exist of the file). We also use this at my job to create "snapshots" of input and output data, so we can reproduce the research later. (We use a simple naming convention to get the time of run, and then label the files with that).
Not sure about launching and then running the GUI with specific scripts in it; I don't think that's a feature you'll find in R, simply because the whole point of running a batch file is usually to avoid the GUI. But hopefully, you can just save the image to disk, and then look at it or pass it to other programs as needed. Hope that helps!

How to run a R language(.r) file using Batch file?

I want to run a R script file (.r) using batch file.
If R.exe is in your PATH, then your windows batch file (.bat) would simply consist of one line:
R CMD BATCH your_r_script.R
otherwise, you need to give the path of R.exe, so for example:
"C:\Program Files\R\R-2.13.0\bin\R.exe" CMD BATCH your_r_script.R
you can add certain input arguments to the BATCH command, such as --no-save, --no-restore
so it would be
R CMD BATCH [options] your_r_script.R
more info on options, etc at http://stat.ethz.ch/R-manual/R-devel/library/utils/html/BATCH.html
Note: R uses the command "BATCH" to non-interactively evaluate a script located in a file. Here we are running the command "BATCH" from a windows .BAT file, but that's merely a coincidence.
An answer to another question suggests using Rscript.exe, so your batch file would contain:
"C:\Program Files\R\R-3.0.2\bin\i386\Rscript.exe" your_script.R
pause
It is a good idea to add R to the windows environment path. In a comment in this question #chase gave a link that explains how to set the path on windows 7. Once R is added to the windows path, your batch file should become simply :
Rscript.exe your_script.R
pause
You can also directly call a R command by using the -e flag. For example this batchfile will tell R to set its current working directory to Documents, then it will print the working directory:
Rscript.exe -e setwd('Documents');getwd()
pause
I struggled with the syntax with the answers below, but this worked for me in the .bat file:
C:\Windows\System32\cmd.exe /k ""path to Rscript.exe"
"path to .R script""
Be sure to place both the path to Rscript.exe and the script in "" together and separately as above.
I doubt you will be able to run it using a batch file.
http://www.fileinfo.com/extension/r
Most known programs that use .r files do so for source code files it looks like. You will probably have to compile it using the program it was written for. I guess you could use a command line compiler from a batch file, but I don't know what language or applications you are using.
If you post the script file or give more information about it, we could probably help you better.

Resources