call R function with parameter from cmd - r

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.

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.

Calling a python function from R with passing the arguments

Is there any package for calling a python function from R by passing the function arguments through R? Now i have directly called the python file using system in R.
a<-system('/home/anaconda3/bin/python /home/Desktop/myfile.py' ,intern = TRUE)
But this myfile.py file is having a function with paramenter. How to specify the parameter in R?
I have tried system('/home/anaconda3/bin/python /home/Desktop/myfile.py argument',wait=FALSE,intern = TRUE) .But it returns 0.
for example I want to pass the number of core that my python script can use:
system(paste('/home/anaconda3/bin/python','home/Desktop/myfile.py',NCORE))
Then in Python Script before launch the function I can read my parameter in this way:
n_core = int(sys.argv[1])
sys.argv is a list in Python, which contains the command-line arguments passed to the script.
please look at reticulate
library(reticulate)
os <- import("os")
os$listdir(".")

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.

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 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