Running R function as command line script with arguments - r

Lets say I have the following script
k <- as.numeric(readline("Start Index: "))
tot <- NULL
for (i in 1:k){
tot <- c(tot, i)
}
write.csv(tot, "test.csv")
I would like to run this script from the command line. How can I run it so that it still asks for the user input (k). Or otherwise can I add the value of k in the CMD command as argument? I am on Linux.

You might find the information in ?commandArgs helpful.
From the description:
Provides access to a copy of the command line arguments supplied
when this R session was invoked.

Related

Is there a function in R to check if there is an error in r script or in a log?

I'm trying to create an if statement to check whether there is any errors in my R script (or error displayed on the console) and also log files if there are to have "error" in a variable and if there isn't to have "no error" in the same variable.
I looked at is.error() however I want to check if an error is shown on the console or log file.
There is no single-stop solution to the best of my knowledge. There are several things you can try:
1) Incorporate your script into your code and use tryCatch or try to catch any errors. More information on error catching and debugging in R can be found here.
2) Execute your script in the system shell via the system command and inspect output caught by setting intern=TRUE.
You can source the script in a new environment :
testscript <- function(scriptpath) {
tryCatch({
# Tests is the script runs without error
source(scriptpath, local = new.env())
message("Script OK")
},
error = function(cond){
message('Script not OK')
message(cond)
})}
for example, content of script.R :
x <- 1
y <- 2
x + z
testscript('script.R')
Script not OK
object 'z' not found

collect output of system rscript command as r object

I am using RStudio in Windows to develop and run a pipeline for multivariate analysis that involve big dataset (90 by ~ 60000 matrices). With matrices of such a size, I got "protection from stack overflow" pretty often. One way of avoid this problem, while still using RStudio as opposite to the regular Rgui, is to run my script(s) using the following syntax
system("Rscript --max-ppsize=500000, my_script.s").
However, running this command results in the script running succesfully, but I cannot get the desired output. If I run the previous command with the following option
opt-< system("Rscript --max-ppsize=500000, my_script.s", internal = TRUE)
I got the standard output to the terminal as output (as a character vector), but not the desired output.
Consider this toy examples:
save the following code in my_script.R
print("first call")
rnorm(15)
print("second call")
rnorm(20)
and run the following code from the console
a <- system("Rscript my_script.R", intern = TRUE)
a
As you can see, the output is a character vector of length 9 with the standard output to the console.
If you modify my_script.R as follow
print("first call")
i_want_this <- rnorm(20)
and then run it again
a <- system("Rscript my_script.R", intern = TRUE)
a
now the only thing stored in a is the output of the print command.
My question is: is there a way to collect the i_want_this variable as an r object (in this case a numeric vector of length 20) ?
A similar question has been asked here, without a satisfying answer.

Running R function with arguments in 32 bit R, inside 64 bit R

Suppose I want to run the function
test.function <- function(arg1){
print(arg1)
}
How can I run, lets say:
test.function("Hello world")
in 32 bit mode, using 64 bit R? I have managed running an entire script in 32 bit mode using
system(paste0(Sys.getenv("R_HOME"), "/bin/i386/Rscript.exe ",'"some_script.R"'))
But how can I change this, so that it can run a function with arguments, instead of an entire script?
EDIT
Following the answer by Roman Luštrik and running
system('Rscript test.script.R "hello"')
Gives me the following error:
Error in winDialog(type = "ok", message = message_text) :
winDialog() cannot be used non-interactively
call: -> check.for.updates.R -> winDialog
Running stopped
Warning message:
running command 'Rscript test.script.R "hello"' had status 1
(The error message was in my native language, so I had to translate a few words, so the text might differ slightly on other systems)
You can't run a specific function only, you will have to create a script. This does not stop you from creating a one-function only script, though.
If you create a script called test.script.R and put it somewhere where you can find it.
args <- commandArgs(trailingOnly = TRUE)
str(args)
test.function <- function(x) {
message("Your input:")
message(x)
}
invisible(sapply(args, test.function))
Open up a terminal window. You can use Windows' cmd.exe (press Windows key and type cmd.exe or Command Prompt or whatever you have in your perhaps localized version of the system). Navigate to where the script is located and run it using the below command.
$ Rscript test.script.R "hello" "hello" "won't you tell me your name" "i hate the doors"
chr [1:4] "hello" "hello" "won't you tell me your name" ...
Your input:
hello
Your input:
hello
Your input:
won't you tell me your name
Your input:
i hate the doors
Or, you could use system to do the same thing through R.
system('Rscript test.script.R "hello" "hello" "won't you tell me your name" "i hate the doors"')
Notice the way I use single and double quotes. Single quotes are on the outer side. This call also assumes the script is located in the workspace where R is currently looking. You can change that using setwd(), though.
I managed to find a solution myself, by modifying Roman Luštrik's solution.
Following his example we have the script called test_script.R:
args <- commandArgs(trailingOnly = TRUE)
test.function <- function(x) {
print(x)
}
args.run <- list(x = args)
mydata <- do.call(test.function, args = args.run)
save(mydata, file = "Data.Rda") # If you need the output to an R object
Then in another script that runs 64 bit R, we can run this function in 32 bit R by:
pathIn32BitRScript <- '"C:/Some path/test_script.R"'
system(paste0(Sys.getenv("R_HOME"), "/bin/i386/Rscript.exe", pathIn32BitRScript, " ", "Hello world") )
load("Data.Rda") # Loads the results into an object called mydata
invisible(file.remove("Data.Rda")) # Deletes the file we created
In this example we have x = "Hello World". In case you have spaces in your path you will need the double quotes as I have in this example.

Error when running (working) R script from command prompt

I am trying to run an R script from the Windows command prompt (the reason is that later on I would like to run the script by using VBA).
After having set up the R environment variable (see the end of the post), the following lines of code saved in R_code.R work perfectly:
library('xlsx')
x <- cbind(rnorm(10),rnorm(10))
write.xlsx(x, 'C:/Temp/output.xlsx')
(in order to run the script and get the resulting xlsx output, I simply type the following command in the Windows command prompt: Rscript C:\Temp\R_code.R).
Now, given that this "toy example" is working as expected, I tried to move to my main goal, which is indeed very similar (to run a simple R script from the command line), but for some reason I cannot succeed.
Again I have to use a specific R package (-copula-, used to sample some correlated random variables) and export the R output into a csv file.
The following script (R_code2.R) works perfectly in R:
library('copula')
par_1 <- list(mean=0, sd=1)
par_2 <- list(mean=0, sd=1)
myCop.norm <- ellipCopula(family='normal', dim=2, dispstr='un', param=c(0.2))
myMvd <- mvdc(myCop.norm,margins=c('norm','norm'),paramMargins=list(par_1,par_2))
x <- rMvdc(10, myMvd)
write.table(x, 'C:/Temp/R_output.csv', row.names=FALSE, col.names=FALSE, sep=',')
Unfortunately, when I try to run the same script from the command prompt as before (Rscript C:\Temp\R_code2.R) I get the following error:
Error in FUN(c("norm", "norm"))[[1L]], ...) :
cannot find the function "existsFunction"
Calls: mvdc -> mvdcCheckM -> mvd.has.marF -> vapply -> FUN
Do you have any idea idea on how to proceed to fix the problem?
Any help is highly appreciated, S.
Setting up the R environment variable (Windows)
For those of you that want to replicate the code, in order to set up the environment variable you have to:
Right click on Computer -> Properties -> Advanced System Settings -> Environment variables
Double click on 'PATH' and add ; followed by the path to your Rscript.exe folder. In my case it is ;C:\Program Files\R\R-3.1.1\bin\x64.
This is a tricky one that has bitten me before. According to the documentation (?Rscript),
Rscript omits the methods package as it takes about 60% of the startup time.
So your better solution IMHO is to add library(methods) near the top of your script.
For those interested, I solved the problem by simply typing the following in the command prompt:
R CMD BATCH C:\Temp\R_code2.R
It is still not clear to me why the previous command does not work. Anyway, once again searching into the R documentation (see here) proves to be an excellent choice!

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