Call a function in R Script from a Batch file - r

I've a batch file that calls R script. It works fine. I need to know how Can I Call a function in R Script from that Batch file in windows? How to call this Function with parameters:
PNLCalcMultipleDatesClient("2010-10-03", "2010-10-05", "XYZ")
This command line works but it doesn't have Function call that is in R Script. Can you please help me to modify this command line in Windows and call above function ?
"\\C1PRDTLS01.axinc.com\Dev\RiskClient\inputCData\PNLCalculation\R\R-3.1.1\bin\R.exe" CMD BATCH --no-save --no-restore "\\C1PRDTLS01.axinc.com\Dev\RiskClient\inputCData\PNLCalculation\RScript\RadarPNLTimeseries.R"
Here is the R Script:
PNLCalcMultipleDatesClient("2010-10-03", "2010-10-05", "Dunavant")
PNLCalcMultipleDatesClient <- function(begindate, enddate, Client)
{
# Do some operation here....
.....
......
}

Here is an example. Here is the Rscript that i have, i tend to save them as txt itself.
## Rscript: Passing arguments to the Rscripts likes args[i]
#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
print(1:args[1])
df=data.frame(1:args[1])
write.csv(df, args[2])
Then your batch file would look like this. Then you feed those arguments either directly to a cmd or create a batch file out of it.
echo off
Rscript rparam.txt 1000 out.csv
For your case, your Rscript(R_with_par.R) would be:
#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
x1=args[1]
x2=args[2]
x3=args[3]
PNLCalcMultipleDatesClient <- function(begindate, enddate, Client)
{
# Do some operation here....
.....
......
}
PNLCalcMultipleDatesClient(as.Date(x1), as.Date(x2), as.character(x3))
And your CMD command would be:
Rscript R_with_par.R 2010-10-03 2010-10-05 Dunavant
You have to make sure that parameters that you pass are in format required by R. Give the path of the R script if you are not in the same directory. Also Rscript is far better choice than R CMD.

Create R Function:
squared <- function(number) {
sqred <- number^2
cat(sqred)
}
squared(as.integer(commandArgs(trailingOnly = TRUE)))
Run R script from command prompt: (Your path could be different)
C:R/bin/RScript.exe" "C:/Rscript/command_line.R" 100
Note: First argument is path of Rscript.exe, Second Argument is path of your R script and third argument is function argument.

Related

Passing arguments to an R script from command lines when the argument is a string

I want to pass arguments to an R script from command lines when the argument is a string
I know that if the argument is a numeric value, I can write something in the command line :
R CMD BATCH "--args CHR=1" rfile.R test.Rout
But I want to input a file name such as "file1.txt" in r command. If I put
R CMD BATCH "--args CHR=1 file="file1.txt" rfile.R test.Rout
It does not work. How can I fix it?
Here is a simple R script which would take string inputs:
args <- commandArgs(trailingOnly = TRUE)
cat(args, sep = "\n")
I save the file as "test.R" in my home directory. In the command line I can then use:
Rscript test.R "file.txt"
The " are optional if your string does not have whitespace. But this would be recognised as two inputs:
Rscript test.R file 1.txt
There is a nice little tutorial from which I took this here.

Passing value to a function through R CMD BATCH

I have a function created in R for test purpose that will get two values, add them and assign the result to a variable and the result will be stored in a csv file. Below is my r code
f2 <- function(x, y) {
args=(commandArgs(TRUE))
z1 <- x + y
z2 <- x + 2*y
b <- list(z1, z2)
write.csv(b,"testfun.csv",row.names=F)
print(z1)
print(z2)
print(b)
}
The code is working fine and i am able to pass the values to my function through r console. However I want to do this using R CMD and not in a r console. This is because i have a web application that will invoke this function on click of a button.
I tried to invoke the function using the below code
Rscript test.R 5 100
and
R CMD BATCH --no-save --no-restore '--args x=3 y=5' test.R test.out &
However the function is not getting invoked and i am not getting the output. When i run the above R CMD BATCH statement i'm getting an error like ''--args'' no such file or directory.
Fatal error: cannot open file ''--args': No such file or directory
So i moved the '--args x=3 y=5' values after the test.R something like
R CMD BATCH --no-save --no-restore test.R '--args x=3 y=5' test.out &
On executing the above i'm getting my r sript saved in the directory and not the my expected output. I tried all the ways from the below link
Passing command line arguments to R CMD BATCH
Can anyone shed some light over this? I need to invoke my function along with some parameter through rscript or r cmd.

call R function with parameter from cmd

I have file a.R with one function:
big_name<-function(name){
big_name<-toupper(toString(name))
return(big_name)
}
How can I call this function from cmd(command prompt or shell) with parameter for example "John", without R opening?
You can do : R -e "source('./big_name.R'); big_name('test')"
If you added R in your system path.

How do I get in R the name of currently executed script when called via `r BATCH script file`

I call a script from a shell command line with
r CMD BATCH myscript.R
What do I have to do in myscript.R to get a character vector with the name of the script (i.e. "myscript.R")?
Note:
I found numerous questions on similar topics, but couldn't find anything that work for me. Particularly from question Determine path of the executing script I got the modified script snippet:
args <- commandArgs(trailingOnly = F)
scriptPath <- sub("^--file=", "", args[grep("^--file=", args)])
but scriptPath is always empty (probably due to the way I call the script via the BATCH command).
A simple example with commandArgs() works fine for me:
myscript.R:
commandArgs()[3]
in the terminal:
R CMD BATCH myscript.R
and then cat myscript.Rout:
commandArgs()[3]
[1] "myscript.R"
I believe if you use Rscript instead of R CMD BATCH it will work for you. I read the same post when I was trying to figure out how set working directory to directory of myscript. Anyway to run Rscript
"....\R-3.0.1\bin\x64\Rscript.exe" Myscript.r > Myscript.r.rout
And here is my code to set working directory to directory of script. I kept trying different alternatives to this then I realized you need to be using Rscript for the bulk of them to work.
args <- commandArgs(trailingOnly = F)
scriptPath <- normalizePath(dirname(sub("^--file=", "", args[grep("^--file=", args)])))
setwd(scriptPath)

Write access to commandArgs?

I know that I can use commandArgs to read the command line arguments passed to a script in R, but I would like to debug a command line script by sourceing it in R and making it run using custom command line arguments. Is there a way of modifying the command line arguments without modifying the script file?
My scripts are normally using the optparse package for actual argument parsing, if that helps.
I'll try and expand what I said in a comment.
The python way of writing scripts usually involves detecting if the file is being run as a script, handling the args, and then calling functions defined in the file. Something like:
def foo(x):
return x*2
if __name__=="__main__":
v = sys.argv[1]
print foo(v)
This has the advantage that you can import the file into an interactive python session and the code in the 'if' block doesn't run. You can then test the foo function interactively.
Now is there a way you can check in R if the file is being run as a script, or being sourced from an interactive session?
foo=function(x){
return(x*2)
}
if(!interactive()){
x = as.numeric(commandArgs(trailingOnly=TRUE)[1])
print(foo(x))
}
If run with Rscript argtest.R 22 will print 44, if you run R interactively and do source("argtest.R") it won't run the code in the if block. Its a nice pattern.
How about simply overwriting it with your own definition, e.g.
commandArgs <- function(trailingOnly=FALSE) {
args<- c("/foo/bar", "baz")
# copied from base:::commandArgs
if (trailingOnly) {
m <- match("--args", args, 0L)
if (m)
args[-seq_len(m)]
else character()
}
else args
}
The simplest solution is to replace source() with system(). Try
system("Rscript file_to_source.R 1 2 3")

Resources