Determine path of the executing script

前端 未结 28 2391
再見小時候
再見小時候 2020-11-22 08:01

I have a script called foo.R that includes another script other.R, which is in the same directory:

#!/usr/bin/env Rscript
message(\         


        
28条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 08:37

    I work in an HPC cluster environment. I develop my code in a different location from where I do my production runs. During development, I'm usually calling R interactively from the command line (not using RStudio). There is lots of source("foo.R") going on.

    During production runs, I usually write a bash script that tries different parameters and runs each set of parameters in a separate directory. The bash script utilizes the workload manager (i.e. SLURM). In this environment, it is trivial to set an environmental variable. With this in mind, the below solution works best for me.

    other.R

    my_message <- function(){
    return("R is awkward")
    }
    

    foo.R

    srcpath = Sys.getenv("R_SRC")
    # Check if runnning w/o setting R_SRC - presumably done in directory of development, i.e. /path/to/R/code
    if(srcpath == ""){
        srcpath="./"
    }
    source(sprintf("%s/other.R", srcpath))
    string = my_message()
    print(string)
    

    If running this from the R interactive shell and within /path/to/R/code, simply do

    > source("foo.R")
    

    If running not from the interactive shell and not running from /path/to/R/code, set the environmental variable R_SRC first, then call Rscript

    $ export R_SRC=/path/to/R/code/
    $ Rscript /path/to/R/code/foo.R
    

提交回复
热议问题