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

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.

Related

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.

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.

How to use knitr from command line with Rscript and command line argument?

I have an R code my_code.R which takes in an argument a file test.txt. I can use:
Rscript -e my_code.R test.txt
and run the script, but i want to use stitch() from knitR to generate the report of the script in pdf/tex.
I have trolled around stack overflow and used following suggestions, but didn't get any results:
Rscript -e "library(knitr);knit('my_code.R "-args arg1=test.txt" ')"
Rscript -e "knitr::stitch('my_code.R "-args arg1=test.txt"')"
Here is another similar discussion on what i want (link), but with option for adding argument(s).
I do not see why this is not possible. Here is my_code.R:
commandArgs(TRUE)
And I simply run
Rscript -e "library(knitr); stitch('my_code.R')" --args foo bar whatever=blabla
I get the output
It seems you did not use double quotes correctly in your original attempt. It should be
Rscript -e "library(knitr); stitch('my_code.R')" --args arg1=test.txt
You can use knit2pdfand pass parameters to the report using its envir argument.
In other words , the solution is to create 2 seperates files an :
R script where you call knit2pdf like this : m_code.R
a markdown report file (.Rnw,.Rmd) : m_code_report.Rnw
m_code.R
This script contains all you R code. The idea, is to create an environment variable "params" , where you put all parameters need to be displayed/presented.
library(knitr)
library(markdown)
ff <- commandArgs(TRUE)[1]
params <- new.env()
e$ff <- ff
## here I pass all the parameters to the report
## I assume that the report and the code R in the same location
## the result pdf also will be in the same location , otherwise you can set
## paths as you like
knit2pdf('m_code_report.Rnw',envir=params) report
m_code_report.Rnw
The report display resulted using variables contained in the environment "params".
\documentclass{article}
\begin{document}
<<>>=
summary(ff)
#
\end{document}
Then you call the Rscript using Rscript for example like this:
Rscript m_code.R "cars"

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