There is plenty of information on how to change the default working directory in R (every time R or RStudio is started, the working directory would change back to default, so one has to run setwd() every time). In RStudio, there is a relevant option in Tools>Global Options>General. The other solutions seem to involve editing the Rprofile.site file. However, all of this requires the user to be capable of finding the Rprofile and editing it, or browsing through the settings, and all the while not messing up.
What I need is a solution for fools students who have no idea how to do this. One might say customizing the environment would be good practise, but this is a very short course, and I'd like it to be as painless as possible to the computer-illiterate souls in the audience.
I have already written a script that downloads all the necessary packages for the course, loads the script in RStudio, downloads and loads a workspace with data and functions. They just have to run it once after installing R+RStudio. For a moment I though this would be a good idea:
cat("setwd(\"the desired working directory\")", file=file.path(Sys.getenv("R_HOME"), "etc", "Rprofile.site"), append=T)
...but this throws Permission Denied, at least under Windows (Program files are protected I guess). The desired solution should be platform independent (most of them have Windows, but some might have Macs or Linux). But most importantly, it should consist of just pasting the script in the console and pressing enter, nothing more complex (hence the fool-proof part of the title).
What about something like
set_default_wd <- function(wd = getwd()) {
text <- paste0(
'local({ setwd("', wd, '") })')
##
if (Sys.info()["sysname"] == "Windows") {
write(
text,
file = paste0(Sys.getenv("HOME"), "\\.Rprofile"),
append = TRUE)
} else {
write(
text,
file = paste0(Sys.getenv("HOME"), "/.Rprofile"),
append = TRUE)
}
}
##
#R> set_default_wd() #set_default_wd("some/file/path")
This should work on Windows and Unix-like systems, and avoid any permissions issues. Really the only requirement on the user's end is to specify a valid file path, which they should (hopefully) be able to work out.
It may be worthwhile to have the option of overwriting the $HOME/.Rprofile
(instead of forcing lines to be appended) in case a malformed file path is given, etc...
set_default_wd <- function(wd = getwd(), overwrite = FALSE) {
text <- paste0(
'local({ setwd("', wd, '") })')
##
if (Sys.info()["sysname"] == "Windows") {
write(
text,
file = paste0(Sys.getenv("HOME"), "\\.Rprofile"),
append = !overwrite)
} else {
write(
text,
file = paste0(Sys.getenv("HOME"), "/.Rprofile"),
append = !overwrite)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With