Will Beason Will Beason - 2 months ago 13
R Question

Find location of current .R file

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:


  1. 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.


  2. Script determines its own location, then sets that as the working directory.

  3. Script analyzes data inside its own directory.

  4. 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:


Answer

somewhere in the "load the script" process, you are passing the name and path of the R script. I'm suggesting to capture that information and then use a wrapper script to execute your main script.

Option 1 (programatically)

the wrapper function that takes as an argument the path and fiile name of the script to execute

FILE <- "~/Desktop/myFolder/InHere/myScript.R"

Option 2 (interactively)

at the start of your wrapper function, let the user click through to the file:

FILE <- file.choose()

THEN:

DIR  <- dirname(FILE)

and there you have your directory/folder and you can execute your script as normal passing DIR as a parameter

Comments