1

I know that this has been asked several times, but I still am not able to get this to work properly. I have a main script that calls other scripts via source(). I am writing code currently that could potentially be used by multiple teams of people, so I would like to save the main and all scripts into a single folder that will be able to be run from any file location. To do this, the Main.R needs to be able to self-identify it's own directory. I have been unsuccessful in getting this to run properly, and I am hoping someone would be able to help me with this.

Main.R

#Main script
source("Hello.R")

Hello.R

#side script to be run
print("Hello World")

The problem is that I can't run "Hello.R" unless I set the directory to the folder containing all my scripts.

MikeJewski
  • 357
  • 2
  • 13
  • you could create a file named "setwd.R" which specifies the correct path to "Hello.R", then if you work on another computer you will just have to change the path inside "setwd.R". – Mamoun Benghezal Feb 03 '16 at 17:24
  • But I can't call setwd.R from Main.R unless I have the path for setwd.R, which would be the same as Hello.R – MikeJewski Feb 03 '16 at 17:34
  • 1
    How about using `getwd()`? – RHertel Feb 03 '16 at 18:17
  • Doesn't give the directory of the current script – MikeJewski Feb 03 '16 at 18:32
  • As noted [previously](http://stackoverflow.com/a/18003224/3965651), somewhere when you load Main.R, you should know it's directory to call it. – desc Feb 04 '16 at 03:22
  • Im not sure if this is beyond the scope of R, but I wanted to make a Main.R that someone who has no idea about R can open the file and run it and not have to change anything, but I guess this is not possible. – MikeJewski Feb 04 '16 at 15:00

1 Answers1

1

If the user can find and run Main.R, then they can find and run Wrapper.R (they have already done the work of identifying the path you want to use). Thus you can use a wrapper script to run Main.R (and file.choose is pretty intuitive for even non-R users):

Wrapper.R

main = file.choose()
main.dir=dirname(main)
source(main,local=TRUE)

Main.R

source(paste(main.dir,'/Hello.R',sep=""))

Hello.R

print('Hello World')
desc
  • 1,190
  • 1
  • 12
  • 26