我已经查看了许多与此相似的问题(见帖子末尾),但我没有找到任何实际完成我需要的解决方案.我根据项目在Windows或Fedora上编码,我为使用Windows和几个Linux发行版的人编写代码.
我的部分工作是为自动分析数据和创建图形的人制作R脚本.最常见的是,我只是向他们发送脚本,它将生成图表.这样,如果数据发生变化或扩展,我不需要为它们重新运行脚本(也可以根据需要进行更改).
问题是我不知道如何获得一个R脚本来找出它自己的位置.能够创建如下工作的代码将非常方便:
这个问题只涉及第2步.只要我能做到这一点,其他所有事情都会顺利进行.有这样的东西会很高兴:
setwd(FindThisScriptsLocation())
Run Code Online (Sandbox Code Playgroud)
该行:源(...,CHDIR = T)已建议在这里,但它不能被用于一个脚本来引用自身,除非它知道自己的路.
以下是一些相关问题:
.R脚本文件在哪里...(处理包)
如何让R识别您的工作目录...(设置默认工作目录)
Rscript:确定执行脚本的路径(一个脚本调用其他脚本;没有找到答案)
有同样的问题,这就是我想出的.它适用于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)
在“加载脚本”过程中的某个地方,您正在传递 R 脚本的名称和路径。我建议捕获该信息,然后使用包装脚本来执行您的主脚本。
将要执行的脚本的路径和文件名作为参数的包装函数
FILE <- "~/Desktop/myFolder/InHere/myScript.R"
Run Code Online (Sandbox Code Playgroud)
在包装函数的开头,让用户点击进入文件:
FILE <- file.choose()
Run Code Online (Sandbox Code Playgroud)
DIR <- dirname(FILE)
Run Code Online (Sandbox Code Playgroud)
在那里你有你的目录/文件夹,你可以像正常传递DIR参数一样执行你的脚本
| 归档时间: |
|
| 查看次数: |
23095 次 |
| 最近记录: |