Automated running of r-scripts - r

I know there are plenty of tutorials around concerning this topic but Im stuck and I think Im overlooking something.
Im playing around with executing r-files. So what I want to do is:
Create an r-script
Run the script through the command line
So i have this script (called "test.R"):
test <- function(){
function(){
x <- ("Hello world")
print(x)
}
}
And now I would like execute this script through the cmd line. However if I open the cmd line, move to the right dir and do
R CMD BATCH "test.R"
It opens the relevant R file but nothing happens! Any thoughts on how I can not only open the file but also execute it right away....
So when I run it I want the console to print "Hello world"

I modified you test.R code to the following
test <- function(){
x <- ("Hello world")
print(x)
}
test() 'Calling function
Then in windows command prompt I typed the command
rscript test.R
and got this output
[1] "Hello world"
Is this what your looking for?

Related

readline does not prompt user input from Rprofile.site in Rstudio

I have this little function in a file:
library(grDevices) # needed in Rprofile.site
readfun <- function()
{
message("interactive: ", interactive()) # tells TRUE
rl <- readline("Write something: ")
message("rl value is: ", rl)
}
readfun()
I can source it in the R console witin Rstudio just fine.
I can write source("thatfile.R") in the Rrofile.site and calling Rterm via R.exe prompts input as expected. (I'm on Windows, btw).
But starting R with Rstudio, it will not prompt for user input.
Instead, the first typed command will not be executed but messaged back.
This could be related to Wait for user input from keyboard in R before next line of code - readline - Rstudio, but I can't find a way to get it to work...

Interactive Debugging in R

I have a toy R script (test.R) as follows:
myString <- "Hello World"
browser()
print(myString)
I want to interactively debug the script, hence the 'browser()' call.
However, when I run the script like this:
Rscript test.R
I just see:
Called from: top level
[1] "Hello World"
i.e. the 'browser()' call seems to get skipped. When I run the script like this:
R -f test.R
I see:
>
> myString <- "Hello World"
> browser()
Called from: top level
Browse[1]> print (myString)
[1] "Hello World"
Browse[1]>
>
But, execution does not stop at 'Browse[1]>' to allow me to debug.
What am I missing here? In python, I can insert "import pdb; pdb.set_trace()" to debug. I am looking for something similar in R.
See this for how to use browser(). You will be able to source('scriptname.R') a script in the R interactive environment on terminal (by running R instead of Rscript scriptname.R) and then browser() will behave very similar to import pdb; pdb.set_trace() . The one major caveat is arguments - you could manually configure that to use the arguments you would supply on the command line by using say if(interactive()) (or there might be other ways to achieve this).

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!

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