Rscript Detect If R Script Is Being Called/Sourced from Another Script

Rscript detect if R script is being called/sourced from another script

EDIT

Okay, this is a LOT more like python's __name__ trick. (Previous answer below, kept for historical reasons.)

function1 <- function(etc,etc) {}
function2 <- function(etc,etc) {}

if (sys.nframe() == 0L) {
library(optparse)
# ...
}

It is about as minimalist as one could hope for, does not require the sourceing script to know anything about it, and seems to work well even when nested.

Other possible mechanisms could be used (additional functions required) by looking at script names, per Rscript: Determine path of the executing script. Many plausible (some really good) solutions exist there, but they all require a pre-defined function not defined in a base package (or non-trivial code included in the script to be sourced). If you want to "assume package X is installed", then your script becomes potentially non-portable.


(Previous answer, I suggest you use above.)

I'll throw this out as a hack ... it's only slightly less janky than your workaround, but it relies on the calling script knowing something of what the called script is testing for.

If the calling script sets a variable:

BEING_SOURCED_FROM_SOMEWHERE <- TRUE

then the called script can check for it:

function1 <- function(etc,etc) {}
function2 <- function(etc,etc) {}

if (! exists("BEING_SOURCED_FROM_SOMEWHERE")) {
library(optparse)
# ...
}

I don't like it. It isn't as flexible as python's

if __name__ == "__main__":
import optparse
# ...

But I think I dislike it less than your use of save and load for function definitions.

call an R Script from an other script

To call an RScript from another script, you need to source it at the beginning:

source("H.R")
# H is now available
G = function(x) {
return(-exp(-1i * x) * Conj(H(x+pi)) )
}

If you want to clean up your functions, you can also build a package containing all your functions.

A little bit more of work, but definitely worth the effort!

How can a script find itself in R running from the command line?

Below is a solution that will give you the correct file directory path when the script is run either with source or with Rscript.

# this is wrapped in a tryCatch. The first expression works when source executes, the
# second expression works when R CMD does it.
full.fpath <- tryCatch(normalizePath(parent.frame(2)$ofile), # works when using source
error=function(e) # works when using R CMD
normalizePath(unlist(strsplit(commandArgs()[grep('^--file=', commandArgs())], '='))[2]))
dirname(full.fpath)

The key to this is the function normalizePath. Given a relative or abbreviated path name, normalizePath will return a valid path or raise an error. When running the script from Rscript, if you give normalizePath the base filename of the current script, it'll return the fullpath, regardless of what your current directory is. It even gets the path right when you supply a relative path to R CMD and there's a script with the same name in the current directory!

In the code above, I extract the filename from one of the strings returned by commandArgs. If you take a look at the output of commandArgs, you'll see that the filename is the 4th argument. The argument is recorded as '--file=yourscript.R', so in the final line above, I split the string on '=' and pull out the file name.

How to include (source) R script in other scripts

Here is one possible way. Use the exists function to check for something unique in your util.R code.

For example:

if(!exists("foo", mode="function")) source("util.R")

(Edited to include mode="function", as Gavin Simpson pointed out)

How to call a R program from another R program?

This should do

if(condition==X){
source("program_A.R")
}else{
source("program_B.R")
}


Related Topics



Leave a reply



Submit