代码之家  ›  专栏  ›  技术社区  ›  nico

获取R脚本的路径

  •  58
  • nico  · 技术社区  · 14 年前

    有没有一种方法可以通过编程方式在脚本内部找到R脚本的路径?

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

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

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

    setwd(getScriptPath())

    那么,是否存在类似的函数?

    8 回复  |  直到 7 年前
        1
  •  23
  •   Boern    9 年前

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

        2
  •  35
  •   rakensi    10 年前

    这对我很有用:

    getSrcDirectory(function(x) {x})
    

    这将在脚本中定义一个匿名函数(不做任何事情),然后确定该函数的源目录,即脚本所在的目录。

        3
  •  26
  •   Richie Cotton Joris Meys    9 年前

    仅限RSTUDIO:

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

    这工作时 宁或 来源 你的文件。

        4
  •  6
  •   Bernhard Kausler    11 年前

    利用rscript的隐式“-file”参数

    使用“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)
    }
    
        5
  •  4
  •   Dirk is no longer here    14 年前

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

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

    您可以对目录执行同样的操作 inst/glade/ 在将成为目录的源中 glade/ 在已安装的包中--和 system.file() 将在安装时为您计算路径,而不考虑操作系统。

        6
  •  3
  •   sietemonos    10 年前

    这个答案对我很好:

    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-

    但我还是不明白什么是系统框架(1)$ofile。我在R文档中没有找到任何关于这个的信息。有人能解释吗?

        7
  •  1
  •   Jerry T    9 年前
    #' 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
    }
    
        8
  •  0
  •   WJ2016    8 年前

    如何使用系统和shell命令?对于WindowsOne,我认为当您在rstudio中打开脚本时,它会将当前shell目录设置为脚本的目录。您可能需要添加cd c:\e.g或要搜索的任何驱动器(例如shell('dir c:\\*file\u name/s',intern=true)-\以转义转义字符)。除非您进一步指定子目录(对于Linux,我从/开始搜索),否则只适用于唯一命名的文件。在任何情况下,如果您知道如何在shell中查找某些内容,那么这就提供了一个布局来在r中查找它并返回目录。无论您是在寻找源代码还是运行脚本,都应该有效,但我还没有充分探索潜在的bug。

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