1

How can I have my Rscript parameters change directories?

If my command-line argument is Rscript test.R "foo1", I want to setwd("~/foo1"), but I get the error that it cannot change working directory.

args<-commandArgs(trailingOnly=TRUE) 
lambda<args[1] 
fileEnd<-args[2] 
replicate<-args[3] 
directory<-args[4] 
setwd(directory)

A sample command-line is Rscript test.R 0 1 10 "~/foo1"

user3746406
  • 81
  • 10

2 Answers2

0

Try this:

# use commandline arguments
args <- commandArgs(TRUE)

# the first argument is the working dir
working.dir <- args[1]

# change the working dir
setwd(file.path("~", working.dir))
rrs
  • 9,615
  • 4
  • 28
  • 38
0

It is not possible to give you a specific answer since you are not providing the key parts of your script. To simplify the troubleshooting, start with adding the full physical path to what you want to change directory. This to secure that the full path works.

General suggestions.

The most structured way is to put an [.Rprofile] file in the directory you will trigger your Rscript. The local [.Rprofile] will be read when Rscript initiates the R terminal session. In [.Rprofile] you need to add [setwd('/yourpath'). This is assumed if you just want to set the wd at start.

If you need to change the [setwd] during the course of your script/s you can of course include them in the R-files. Remember though that Rstudio and R terminal behaves different when comes to [load/save]. Rstudio acts dynamically when you change something through its console and show directly the changes in the global environment window.

For Rscript triggered from terminal you will have to make sure that for each script you add [load/save] for R to compensate that it losses the environment when it is not in a running session with Rscript.

The difference behaviour between Rstudio and R terminal is important to keep in mind, especially if you test scenarios in Rstudio and expect it to work the same way in R-terminal.

Toolbox
  • 2,333
  • 12
  • 26