I have some R code inside a file called analyse.r. I would like to be able to, from the command line (CMD), run the code in that file without having to pass through the R terminal and I would also like to be able to pass parameters and use those parameters in my code, something like the following pseudocode:
C:\>(execute r script) analyse.r C:\file.txt
and this would execute the script and pass "C:\file.txt" as a parameter to the script and then it could use it to do some further processing on it.
How do I accomplish this?
You want
Rscript.exe
.You can control the output from within the script -- see
sink()
and its documentation.You can access command-arguments via
commandArgs()
.You can control command-line arguments more finely via the getopt and optparse packages.
If everything else fails, consider reading the manuals or contributed documentation
There are two ways to run a R script from command line (windows or linux shell.)
1) R CMD way R CMD BATCH followed by R script name. The output from this can also be piped to other files as needed.
This way however is a bit old and using Rscript is getting more popular.
2) Rscript way (This is supported in all platforms. The following example however is tested only for Linux) This example involves passing path of csv file, the function name and the attribute(row or column) index of the csv file on which this function should work.
Contents of test.csv file x1,x2 1,2 3,4 5,6 7,8
Compose an R file “a.R” whose contents are
Runing the following on the linux shell Rscript a.R /home/impadmin/test.csv cols 1 gives you passed the following at the command line /home/impadmin/test.csv cols 1 Matrix is: x1 x2 1 1 2 2 3 4 3 5 6 4 7 8 Dimensions of the matrix are 4 2 This function will print sum of the column whose index is passed from commandline processing...column sums 16
Runing the following on the linux shell Rscript a.R /home/impadmin/test.csv rows 2 gives you passed the following at the command line /home/impadmin/test.csv rows 2 Matrix is: x1 x2 1 1 2 2 3 4 3 5 6 4 7 8 Dimensions of the matrix are 4 2 This function will print sum of the row whose index is passed from commandline processing...row sums 7
We can also make the R script executable as follows (on linux) chmod a+x a.R and run the second example again as ./a.R /home/impadmin/test.csv rows 2
This should also work for windows command prompt..
Identify where R is install. For window 7 the path could be
save the following in a text file
No run the following command in windows cmd
This will print the following