Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch R Script - setting the working directory and selecting output folder

I've been digging into several places for 2 simple needs but couldn't find a final answer.

I'm running an R script in batch mode. Not sure whether my solution is the best one but I'm using R CMD BATCH as per http://stat.ethz.ch/R-manual/R-patched/library/utils/html/BATCH.html included in a bat file.

First I'd like to have the directory where the R script is saved set up as the working directory rather than where the bat file is saved.

Secondly I'd like to divert all the output from the R script (csv files and charts) to a specific directory other than the working directory. I cannot find any options for such basic requirement.

The final idea is to be able to run the bat file across different computers no matter where the R script is saved.

Thanks

like image 821
pcava Avatar asked May 29 '13 09:05

pcava


People also ask

Which command is used to change the current working directory of R?

The cd newDir command will change the current working directory.

What is the working directory in R?

The working directory in R is the folder where you are working. Hence, it's the place (the environment) where you have to store your files of your project in order to load them or where your R objects will be saved.


1 Answers

You don't give code so my answer will be just an advise or what I would do for such job.

  1. Use Rscript.exe it is the way to go for batch script. R CMD is a sort of legacy tool.
  2. You don't need to set or change the working directory. It is a source of problems
  3. You can launch you bat file where you want and within it you go to R script location using cd for example you bat file can be like:

    cd R_SCRIPT_PATH
    Rscript youscript.R arg1 arg2
    
  4. You can use one of the script argument as an output directory for your result files. For example inside your script you do somehing like this:

    args <- commandArgs(trailingOnly = TRUE)
    resultpath <- as.character(args[1])
    .....
    write.table(res1, file=paste(resultpath,'res1.csv',sep='/')
    
like image 116
agstudy Avatar answered Oct 07 '22 05:10

agstudy