6

Possible Duplicate:
Rscript: Determine path of the executing script

Always I run an R script, it take My Documents as working directory.

When I run the script, I want to get the script path and change the working directory to it. How I can do this?

I want this to run the scripts in same folder with the source() function.

Community
  • 1
  • 1
Renato Dinhani
  • 35,057
  • 55
  • 139
  • 199
  • If you use ESS there's a macro to do this. Probably for other editors too. – baptiste Nov 10 '11 at 23:24
  • 1
    Perhaps: `args <- commandArgs(trailingOnly = F) ; scriptPath <- dirname(sub("--file=","",args[grep("--file",args)]))` From one of the answers in the above cited SO link. – IRTFM Nov 10 '11 at 23:35

2 Answers2

12

if you run script by source, then try source(file, chdir = TRUE).

kohske
  • 65,572
  • 8
  • 165
  • 155
2

What the hex, I try putting it in as a solution:

args <- commandArgs(trailingOnly = F)
 scriptPath <- dirname(sub("--file=","",args[grep("--file",args)]))
IRTFM
  • 258,963
  • 21
  • 364
  • 487