首页 文章

获取R脚本的路径

提问于
浏览
57

有没有办法以编程方式在脚本本身内找到R脚本的路径?

我问这个是因为我有几个脚本使用 RGtk2 并从.glade文件加载GUI .

在这些脚本中,我不得不在开头放置 setwd("path/to/the/script") 指令,否则将找不到.glade文件(位于同一目录中) .

这很好,但如果我将脚本移动到另一个目录或另一台计算机,我必须更改路径 . 我知道,这不是什么大不了的事,但有一些东西会很好:

setwd(getScriptPath())

那么,是否存在类似的功能?

8 回答

  • 33

    这个答案对我很好:

    script.dir <- dirname(sys.frame(1)$ofile)
    

    注意:必须获取脚本才能返回正确的路径

    我找到了:https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-

    但我仍然不明白什么是sys.frame(1)$ ofile . 我在R文档中没有找到任何相关内容 . 有人可以解释一下吗?

  • 25

    如何使用系统和shell命令?使用windows one,我认为当你在RStudio中打开脚本时,它会将当前的shell目录设置为脚本目录 . 您可能必须添加cd C:\例如或您要搜索的任何驱动器(例如shell('dir C:\ * file_name / s',intern = TRUE) - \以转义转义字符) . 除非您进一步指定子目录(对于我从/开始搜索的Linux),否则仅适用于唯一命名的文件 . 在任何情况下,如果你知道如何在shell中找到一些东西,这提供了一个布局,可以在R中找到它并返回目录 . 无论您是采购还是运行脚本,都应该工作,但我还没有充分发现潜在的错误 .

    #Get operating system
    OS<-Sys.info()
    win<-length(grep("Windows",OS))
    lin<-length(grep("Linux",OS))
    
    #Find path of data directory
    #Linux Bash Commands
    if(lin==1){
      file_path<-system("find / -name 'file_name'", intern = TRUE)
      data_directory<-gsub('/file_name',"",file_path)
    }
    #Windows Command Prompt Commands
    if(win==1){
      file_path<-shell('dir file_name /s', intern = TRUE)
      file_path<-file_path[4]
      file_path<-gsub(" Directory of ","",file_path)
      filepath<-gsub("\\\\","/",file_path)
      data_directory<-file_path
    }
    
    #Change working directory to location of data and sources  
    setwd(data_directory)
    
  • 4

    这对我有用:

    getSrcDirectory(function(x) {x})
    

    这在脚本中定义了一个匿名函数(什么都不做),然后确定该函数的源目录,即脚本所在的目录 .

  • 21

    仅适用于RStudio:

    setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
    

    这在运行或源文件时有效 .

  • 6
    #' current script dir
    #' @param
    #' @return
    #' @examples
    #' works with source() or in RStudio Run selection
    #' @export
    z.csd <- function() {
        # http://stackoverflow.com/questions/1815606/rscript-determine-path-of-the-executing-script
        # must work with source()
        if (!is.null(res <- .thisfile_source())) res
        else if (!is.null(res <- .thisfile_rscript())) dirname(res)
        # http://stackoverflow.com/a/35842176/2292993  
        # RStudio only, can work without source()
        else dirname(rstudioapi::getActiveDocumentContext()$path)
    }
    # Helper functions
    .thisfile_source <- function() {
        for (i in -(1:sys.nframe())) {
            if (identical(sys.function(i), base::source))
                return (normalizePath(sys.frame(i)$ofile))
        }
    
        NULL
    }
    .thisfile_rscript <- function() {
        cmdArgs <- commandArgs(trailingOnly = FALSE)
        cmdArgsTrailing <- commandArgs(trailingOnly = TRUE)
        cmdArgs <- cmdArgs[seq.int(from=1, length.out=length(cmdArgs) - length(cmdArgsTrailing))]
        res <- gsub("^(?:--file=(.*)|.*)$", "\\1", cmdArgs)
    
        # If multiple --file arguments are given, R uses the last one
        res <- tail(res[res != ""], 1)
        if (length(res) > 0)
            return (res)
    
        NULL
    }
    
  • 1

    使用 source("yourfile.R", chdir = T)

  • 3

    如果将代码包装在包中,则始终可以查询包目录的某些部分 .
    以下是RGtk2包中的示例:

    > system.file("ui", "demo.ui", package="RGtk2")
    [1] "C:/opt/R/library/RGtk2/ui/demo.ui"
    >
    

    您可以对源中的目录 inst/glade/ 执行相同操作,该目录将成为已安装软件包中的目录 glade/ - 并且 system.file() 将在安装时为您计算路径,而与操作系统无关 .

  • 0

    Exploit the implicit "--file" argument of Rscript

    使用"Rscript"(Rscript doc)调用脚本时,脚本的完整路径将作为系统参数给出 . 以下函数利用此功能提取脚本目录:

    getScriptPath <- function(){
        cmd.args <- commandArgs()
        m <- regexpr("(?<=^--file=).+", cmd.args, perl=TRUE)
        script.dir <- dirname(regmatches(cmd.args, m))
        if(length(script.dir) == 0) stop("can't determine script dir: please call the script with Rscript")
        if(length(script.dir) > 1) stop("can't determine script dir: more than one '--file' argument detected")
        return(script.dir)
    }
    

相关问题