running an R script from another directory

纵然是瞬间 提交于 2019-12-04 05:27:18

问题


Here's an example with a couple of scripts

test.R ==>
source("incl.R", chdir=TRUE)
print("test.R - main script")

incl.R ==>
print("incl.R - included")

They are both in the same directory. When I run it from that directory using Rscript --vanilla test.R, it works fine. I would like to create multiple subdirectories (run1, run2, run3, ...) and run my original scripts for different parameter values. Suppose I cd run1 and then try to run the script, I get

C:\Downloads\scripts\run1>Rscript --vanilla ..\test.R
Error in file(filename, "r", encoding = encoding) :
  cannot open the connection
Calls: source -> file
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'incl.R': No such file or directory
Execution halted

How do I get this to work?


回答1:


I am not sure that I unserstand your problem correctly. I assume that you have your scripts test.R and incl.R in the same folder and then run test.R using Rscript from some other folder. test.R should figure out where test.R (and thus incl.R) is stored and then source incl.R.

The trick is that you have to put the full path to the script test.R as an argument to your call of Rscript. It is possible to get this argument using commandArgs and then construct the path to incl.R from it:

args <- commandArgs(trailingOnly=FALSE)
file.arg <- grep("--file=",args,value=TRUE)
incl.path <- gsub("--file=(.*)test.R","\\1incl.R",file.arg)
source(incl.path,chdir=TRUE)

In your example in the question, you call the script by Rscript --vanilla ..\test.R. args will then be a character vector that contains the element "--file=../test.R". With grep I grab this element and then use gsub to obtain the path "../incl.R" from it. This path can then be used in source.



来源:https://stackoverflow.com/questions/30264144/running-an-r-script-from-another-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!