Passing value to a function through R CMD BATCH - r

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.

Related

system() in r always returns error but bash terminal() works

I would like to rename files based on list 'mappingFile.csv'. Actually, I do most of the work in r so tried to run it in rstudio but it returns error, while bash terminal does work as expected.
y <- 'awk -F',' 'system("mv " $1 " " $2)' mappingFile.csv'
cat(y)
system(y)
#It return error
Error: unexpected symbol in "y <- "awk -F',' 'system("mv"
Another example when I try to download some files from r using system command
y <- 'gdc-client download -m manifest.txt'
system(y)
#it also return error
sh: 1: x: not found Warning message: In system("x") : r
Only some bash commands run in system or system2 in r.
Can someone suggest How do I fix it?

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.

Call a function in R Script from a Batch file

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.

Return a dataframe from R to a shell script as a variable

I am writing a shell script which contains commands to run series of R scripts. These R scripts are interlinked as, the first R script should return a dataframe to shell script variable and I want to pass that variable to second R script.
I tried doing this by using cat function in first Rscript. This handles strings and numbers but not dataframes. I want to return and pass dataframes. Is there any way that I could do this.
Below is the sample R scripts and shell script.
Here is my shell script: shell1.sh
#!/bin/sh
v1=$(R --slave --no-save < DataExtraction.R)
v2=$(R --slave --no-save < DataTransformation.R $v1)
echo $v2
DataExtraction.R:
df1 <- mtcars
cat(df1)
DataTransformation.R:
args <- commandArgs(TRUE)
df2 <-args[1]
abc <- df2$mpg
cat(abc)
when I run the shell script I should see the content of mtcars$mpg printed on the terminal.

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)

Resources