I have to hand in my R-program on CD-ROM. This CD-ROM should also contain the original datasets. To start the program, the working directory has to be set to load the datasets. Unfortunately, I do not know how to set the working directory to a specific CD-ROM, so that my supervisor can only run the program without having to modify anything. Does anyone have an idea?
-
perhaps https://github.com/krlmlr/rprojroot will help? – hrbrmstr Aug 08 '16 at 16:40
-
Perfect! Thank you!! – prznrl Aug 08 '16 at 16:47
-
@hrbrmstr very instructing link, from what i understood it might solve the OP's problem if 1/ the `rprojroot` package is already installed, 2/ if the script and data are organised as an R project, is that right? – agenis Aug 08 '16 at 21:01
-
Aye. Though I believe it handles other types of dir structures too – hrbrmstr Aug 08 '16 at 21:03
-
@prznrl Hi, if any answer solves your problem can you click on "accept it" so that other people can see it? thanks – agenis Sep 06 '17 at 13:11
2 Answers
You can use setwd function for this purpose or if you like to set it interactively, try choose.dir
function within the setwd
.

- 3,557
- 2
- 20
- 29
I turned my comment into an answer:
You want an R script that can work just by clicking the Run button on a script located on a CD-ROM. The first idea is to start by defining the working directory with the drive letter commonly used for CD-ROMs:
setwd("E:/project/") # remember that in R the slash is inverted for the paths
However, the CD-ROM drive name can vary across the computers (D:, E:, ...) and it might not work. You could for instance use a prompt to ask for a user input like this (be careful because the behaviour can vary wether you run it as a whole, line by line, or source it):
CDROM <- readline(prompt = "Specify the letter of the CR-ROM drive: ")
setwd(paste0(CDROM, ":/project/"))
If you don't want any action from the user, there is a way for R to automatically find the repertory where the active script is located (see this question here, you'll see that it's not as simple as it seems). It might work with the following line, but only if the user sources the script instead of running it:
setwd(dirname(sys.frame(1)$ofile))
Personnally, I would simply add a comment line at the beginning of the script telling to click on the R-studio menu (most people use it):
session > set working directory > to source file location
Hope it helps!