I've looked through many questions similar to this (see end of post), but I haven't found any solutions that actually accomplish what I need. I code on either Windows or Fedora depending on the project, and I code for people who use Windows and several Linux distributions.
Part of my job is making R scripts for people that automatically analyze data and create graphs. Most commonly, I'll just send them the script and it will generate the graph. This way, if the data changes or expands, I don't need to re-run the script for them (also, they can make changes as needed).
The problem is that I don't know how to get an R-script to find out where itself is located. It would be very convenient to just be able to create code that works as follows:
- User saves script to folder containing data, then runs script.
- I usually just email the script to the person I'm working with.
- They save the script to a folder containing the data they want analyzed/graphed.
- Ideally, they would just launch R, load the script, then run the script.
- Script determines its own location, then sets that as the working directory.
- Script analyzes data inside its own directory.
- Script generates graph(s) and saves it to its own directory.
This question only deals with Step 2. Everything else flows nicely as long as I can accomplish that. It would be nice to have something such as:
setwd(FindThisScriptsLocation())
The line: source(..., chdir = T) has been suggested here, but it can't be used for a script to reference itself unless it knew its own path.
Here are some related questions:
Where is the .R script file ... (deals with packages)
How to get R to recognize your working directory ... (setting default working directory)
Rscript: Determine path of executing script (one script calling others; no answer found)
source
d file – Joshua Ulrichsave.image
) that contains a function they can call? As long as the.RData
files are associated with R, they can just double-click the file after saving it in whatever directory, then call the function. – Joshua Ulrich