Stefano Lombardi
Stefano Lombardi

Reputation: 1591

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:

  1. Right click on Computer -> Properties -> Advanced System Settings -> Environment variables
  2. 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.

Upvotes: 1

Views: 2370

Answers (2)

flodel
flodel

Reputation: 89057

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.

Upvotes: 2

Stefano Lombardi
Stefano Lombardi

Reputation: 1591

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!

Upvotes: 1

Related Questions