查找当前.R文件的位置

Wil*_*son 19 r

我已经查看了许多与此相似的问题(见帖子末尾),但我没有找到任何实际完成我需要的解决方案.我根据项目在Windows或Fedora上编码,我为使用Windows和几个Linux发行版的人编写代码.

我的部分工作是为自动分析数据和创建图形的人制作R脚本.最常见的是,我只是向他们发送脚本,它将生成图表.这样,如果数据发生变化或扩展,我不需要为它们重新运行脚本(也可以根据需要进行更改).

问题是我不知道如何获得一个R脚本来找出它自己的位置.能够创建如下工作的代码将非常方便:

  1. 用户将脚本保存到包含数据的文件夹,然后运行脚本.
    • 我通常只是将脚本通过电子邮件发送给我正在使用的人.
    • 他们将脚本保存到包含他们想要分析/绘制的数据的文件夹中.
    • 理想情况下,他们只需启动R,加载脚本,然后运行脚本.
  2. 脚本确定自己的位置,然后将其设置为工作目录.
  3. 脚本分析其自己目录中的数据.
  4. 脚本生成图形并将其保存到自己的目录中.

这个问题只涉及第2步.只要我能做到这一点,其他所有事情都会顺利进行.有这样的东西会很高兴:

setwd(FindThisScriptsLocation())
Run Code Online (Sandbox Code Playgroud)

该行:源(...,CHDIR = T)已建议在这里,但它不能被用于一个脚本来引用自身,除非它知道自己的路.

以下是一些相关问题:

Don*_*onJ 9

有同样的问题,这就是我想出的.它适用于Windows和Linux上的source()和rmarkdwon :: render().

更新:函数get_scriptpath()现在作为我在CRAN上的envDocument包的一部分提供.请参阅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)
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*rta 5

“加载脚本”过程中的某个地方,您正在传递 R 脚本的名称和路径。我建议捕获该信息,然后使用包装脚本来执行您的主脚本。

选项 1(以编程方式)

将要执行的脚本的路径和文件名作为参数的包装函数

FILE <- "~/Desktop/myFolder/InHere/myScript.R"
Run Code Online (Sandbox Code Playgroud)

选项 2(交互)

在包装函数的开头,让用户点击进入文件:

FILE <- file.choose()
Run Code Online (Sandbox Code Playgroud)

然后:

DIR  <- dirname(FILE)
Run Code Online (Sandbox Code Playgroud)

在那里你有你的目录/文件夹,你可以像正常传递DIR参数一样执行你的脚本