Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find location of current .R file

Tags:

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:

  • 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)

like image 851
Will Beason Avatar asked Aug 01 '13 17:08

Will Beason


People also ask

How do I find the location of a file in RStudio?

You can use getwd() (to find the current path of the R process) or file. choose() to interactively find the file (it will return a character of the full path to the file). If you don't want to learn from this and/or do it with different files all the time, then you can short-circuit it with read.

How do you find the current working directory of your R project?

The current working directory is displayed by the RStudio IDE within the title region of the Console pane. You can also check your current working directory by running the command getwd() in the console. There are a number of ways to change the current working directory: Use the setwd R function.

How do I find an Rscript file in a typical file system?

Location of the R Script FileThe R script file is located in the R script's directory, as specified in the _RScriptFile parameter for the R script's metric in MicroStrategy.


2 Answers

Had the same problem, here's what I came up with. It works with source() and rmarkdwon::render() on windows and on linux.

Update: the function get_scriptpath() is now available as part of my envDocument package on CRAN. See https://cran.r-project.org/package=envDocument

#' Get the path of the calling script #'  #' \code{get_scriptpath} returns the full path of the script that called this function (if any) #' or NULL if path is not available #'  #' @examples  #' mypath <- get_scriptpath() #' @export #'  get_scriptpath <- function() {   # location of script can depend on how it was invoked:   # source() and knit() put it in sys.calls()   path <- NULL    if(!is.null(sys.calls())) {     # get name of script - hope this is consisitent!     path <- as.character(sys.call(1))[2]      # make sure we got a file that ends in .R, .Rmd or .Rnw     if (grepl("..+\\.[R|Rmd|Rnw]", path, perl=TRUE, ignore.case = TRUE) )  {       return(path)     } else {        message("Obtained value for path does not end with .R, .Rmd or .Rnw: ", path)     }   } else{     # Rscript and R -f put it in commandArgs     args <- commandArgs(trailingOnly = FALSE)   }   return(path) } 
like image 151
DonJ Avatar answered Oct 27 '22 07:10

DonJ


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

like image 20
Ricardo Saporta Avatar answered Oct 27 '22 06:10

Ricardo Saporta