获取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()
将在安装时为您计算路径,而不考虑操作系统。如果将代码包装在包中,您始终可以查询包目录的部分内容。以下是来自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)
使用源代码(“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利用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这个答案对我来说很好:
script.dir <- dirname(sys.frame(1)$ofile)
script.dir这对我很有用:
getSrcDirectory(function(x) {x})
这在脚本中定义了一个匿名函数(不执行任何操作),然后确定该函数的源目录,即脚本所在的目录。这对我很有用:
getSrcDirectory(function(x) {x})
这将在脚本中定义一个匿名函数(不执行任何操作),然后确定该函数的源目录,即脚本所在的目录。仅适用于RStudio:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
这在运行或源文件时有效。仅适用于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
}
这在运行或源文件时起作用。#“当前脚本目录”
#' 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、 当前脚本目录
#“@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)
#获取操作系统
使用系统和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感谢您提供该函数,尽管我不得不对其进行一些调整,如下所示(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(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")))
在我的例子中,我需要一种方法将正在执行的文件复制到