获取R脚本的路径
有没有一种方法可以通过编程在脚本本身中找到R脚本的路径 我这样问是因为我有几个脚本使用获取R脚本的路径,r,path,R,Path,有没有一种方法可以通过编程在脚本本身中找到R脚本的路径 我这样问是因为我有几个脚本使用RGtk2并从.glade文件加载GUI 在这些脚本中,我必须在开头添加setwd(“path/to/the/script”)指令,否则将找不到.glade文件(位于同一目录中) 这很好,但是如果我将脚本移动到另一个目录或另一台计算机,我必须更改路径。我知道,这没什么大不了的,但如果有这样的东西就好了: setwd(getScriptPath()) 那么,是否存在类似的函数呢?如果将代码封装在包中,则始终可以查
RGtk2
并从.glade文件加载GUI
在这些脚本中,我必须在开头添加setwd(“path/to/the/script”)
指令,否则将找不到.glade文件(位于同一目录中)
这很好,但是如果我将脚本移动到另一个目录或另一台计算机,我必须更改路径。我知道,这没什么大不了的,但如果有这样的东西就好了:
setwd(getScriptPath())
那么,是否存在类似的函数呢?如果将代码封装在包中,则始终可以查询包目录的部分内容。
以下是来自RGtk2包的示例:
> system.file("ui", "demo.ui", package="RGtk2")
[1] "C:/opt/R/library/RGtk2/ui/demo.ui"
>
您可以对源代码中的目录
inst/glade/
执行相同的操作,该目录将成为安装包中的目录glade/
,并且system.file()
将在安装时为您计算路径,而不考虑操作系统。使用源代码(“yourfile.R”,chdir=T)
利用Rscript的隐式“-file”参数
使用“Rscript”()调用脚本时,脚本的完整路径作为系统参数给出。以下函数利用此函数提取脚本目录:
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)
}
getScriptPath这个答案对我来说很好:
script.dir <- dirname(sys.frame(1)$ofile)
script.dir这对我很有用:
getSrcDirectory(function(x) {x})
这将在脚本中定义一个匿名函数(不执行任何操作),然后确定该函数的源目录,即脚本所在的目录。仅适用于RStudio:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
这在运行或源文件时起作用。#“当前脚本目录”
#' 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
}
#“@param
#“@返回
#“@示例
#'与source()或RStudio运行选择一起使用
#“@出口
z、 csd如何使用系统和shell命令?对于windows one,我认为当您在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)
#获取操作系统
OS感谢您提供的功能,尽管我不得不对其进行一些调整,如下所示(W10):
#Windows命令提示符命令
如果(win==1){
file_path这些解决方案中有很多已经有好几年的历史了。虽然有些可能仍然有效,但有充分的理由反对使用它们中的每一个(参见下面的链接源代码)。我有最好的解决方案(也来自源代码):使用这里的库
原始示例代码:
library(ggplot2)
setwd("/Users/jenny/cuddly_broccoli/verbose_funicular/foofy/data")
df <- read.delim("raw_foofy_data.csv")
库(ggplot2)
setwd(“/Users/jenny/cuddly_-brocoli/verbose_-funcill/foofy/data”)
df在我的例子中,我需要一种复制执行文件的方法来备份原始脚本及其输出。这在研究中是相对重要的。在命令行上运行脚本时,对我有效的方法是这里介绍的其他解决方案的混合,如下所示:
library(scriptName)
file_dir <- gsub("\\", "/", fileSnapshot()$path, fixed=TRUE)
file.copy(from = file.path(file_dir, scriptName::current_filename()) ,
to = file.path(new_dir, scriptName::current_filename()))
file.copy(from = file.path(current_dir, current_filename()) ,
to = file.path(new_dir, subDir, paste0(current_filename(),"_", Sys.time(), ".R")))
我知道这个问题在这一点上已经过时了,但我想回答这个问题,因为我制作了一个程序包来处理这个问题。它被称为“this.path”,它可以在CRAN上使用,因此它可以像任何其他程序包一样安装,使用:
install.packages(“this.path”)
当从命令行//终端(Rscript)RStudio、RGui运行R时,它应该检索执行脚本的文件名,当使用“source”时。谢谢Dirk。我真的必须开始考虑将我的脚本放在一个包中…我从你的回答中假设没有一种方法可以在包外执行?你可以捏造其他东西--设置一个环境变量并查询它,或者取消将脚本名称提供给R的参数的parse,或者…但是为什么不要使用简单、经过测试、可靠且专门制造的东西?;-)哦,当然,我只是想知道是否还有其他解决方案!谢谢!@nico我是R的新手,我想做类似的事情。我尝试了这个解决方案,但我得到了一个错误:“…”在不正确的上下文中使用
,你能评论一下问题所在吗d be?这并不广泛适用,尤其是问题的标题——你不能在脚本本身中使用它——如果你知道路径(文件的源代码),你显然也可以设置路径。@hadley我就是这么做的。不幸的是,这种假设并不总是有效的(在使用源代码时会有效),不正确的工作目录使我很讨厌与非技术同事共享.r、.rmd等,他们会打开我发送的.r脚本,并在执行所有行时设置以前的WD,从而导致相对路径失败。因此,PHP中类似于\uuuuu DIR\uuuuu
的东西会很有用,但是的,如果可能的话,会有黑客行为。@hadley实际上没有。项目将WD设置为项目目录,该目录与项目子文件夹中的源文件不同。因此,我将用于Rstudio项目的相对路径与knitr使用的路径不同。不过,最重要的是,如果WD已更改,则无法通过编程将其重置为正确的路径。我对此表示感谢。我对该功能属于何处没有坚定的信念,但这是一个讨厌的问题。我认为这不是一个很好的解决方案,因为需要给出当前文件的名称。如果重命名该文件会怎么样?它将不再工作。此外,当程序在RStudio中运行时,它也不工作。这在inter中特别有用活动会话,如使用Rstudio时。似乎许多
library(scriptName)
file_dir <- gsub("\\", "/", fileSnapshot()$path, fixed=TRUE)
file.copy(from = file.path(file_dir, scriptName::current_filename()) ,
to = file.path(new_dir, scriptName::current_filename()))
file.copy(from = file.path(current_dir, current_filename()) ,
to = file.path(new_dir, subDir, paste0(current_filename(),"_", Sys.time(), ".R")))