简体   繁体   English

用于在 Rstudio 中将工作目录设置为源文件位置的 R 命令

[英]R command for setting working directory to source file location in Rstudio

I am working out some tutorials in R. Each R code is contained in a specific folder.我正在用 R 编写一些教程。每个 R 代码都包含在一个特定的文件夹中。 There are data files and other files in there.里面有数据文件和其他文件。 I want to open the .r file and source it such that I do not have to change the working directory in Rstudio as shown below:我想打开.r文件并获取它,这样我就不必更改 Rstudio 中的工作目录,如下所示:

在此处输入图像描述

Is there a way to specify my working directory automatically in R.有没有办法在 R 中自动指定我的工作目录。

To get the location of a script being sourced, you can use utils::getSrcDirectory or utils::getSrcFilename .要获取源脚本的位置,您可以使用utils::getSrcDirectoryutils::getSrcFilename So changing the working directory to that of the current file can be done with:因此,可以通过以下方式将工作目录更改为当前文件的工作目录:

setwd(getSrcDirectory()[1])

This does not work in RStudio if you Run the code rather than Source ing it.如果您运行代码而不是Source ,这在 RStudio 中不起作用。 For that, you need to use rstudioapi::getActiveDocumentContext .为此,您需要使用rstudioapi::getActiveDocumentContext

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

This second solution requires that you are using RStudio as your IDE, of course.当然,第二种解决方案要求您使用 RStudio 作为 IDE。

I know this question is outdated, but I was searching for a solution for that as well and Google lists this at the very top:我知道这个问题已经过时了,但我也在寻找解决方案,谷歌将其列在最上面:

this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)

put that somewhere into the file (best would be the beginning, though), so that the wd is changed according to that file.将其放入文件的某处(不过最好是开头),以便根据该文件更改 wd。

According to the comments, this might not necessarily work on every platform (Windows seems to work, Linux/Mac for some).根据评论,这可能不一定适用于每个平台(Windows 似乎可以,Linux/Mac 对某些平台有效)。 Keep in mind that this solution is for 'sourcing' the files, not necessarily for running chunks in that file.请记住,此解决方案用于“采购”文件,不一定用于在该文件中运行块。

see also get filename and path of `source`d file另见获取 `source`d 文件的文件名和路径

For rstudio , you can automatically set your working directory to the script directory using rstudioapi like that:对于rstudio ,您可以使用rstudioapi自动将工作目录设置为脚本目录,如下所示:

library(rstudioapi)

# Getting the path of your current open file
current_path = rstudioapi::getActiveDocumentContext()$path 
setwd(dirname(current_path ))
print( getwd() )

This works when Running or Sourceing your file.这在运行或获取文件时有效。

You need to install the package rstudioapi first.您需要先安装包 rstudioapi。 Notice I print the path to be 100% sure I'm at the right place, but this is optional.请注意,我打印路径是为了 100% 确定我在正确的位置,但这是可选的。

dirname(rstudioapi::getActiveDocumentContext()$path)

works for me but if you don't want to use rstudioapi and you are not in a proyect, you can use the symbol ~ in your path.对我有用,但如果你不想使用rstudioapi并且你不在项目中,你可以在你的路径中使用符号 ~ 。 The symbol ~ refers to the default RStudio working directory (at least on Windows).符号 ~ 指的是默认的 RStudio 工作目录(至少在 Windows 上是这样)。

RStudio 选项

If your RStudio working directory is "D:/Documents", setwd("~/proyect1") is the same as setwd("D:/Documents/proyect1").如果您的 RStudio 工作目录是“D:/Documents”, setwd("~/proyect1")与 setwd("D:/Documents/proyect1") 相同。

Once you set that, you can navigate to a subdirectory: read.csv("DATA/mydata.csv") .设置完成后,您可以导航到子目录: read.csv("DATA/mydata.csv") Is the same as read.csv("D:/Documents/proyect1/DATA/mydata.csv") .read.csv("D:/Documents/proyect1/DATA/mydata.csv")相同。

If you want to navigate to a parent folder, you can use "../" .如果要导航到父文件夹,可以使用"../" For example: read.csv("../olddata/DATA/mydata.csv") which is the same as read.csv("D:/Documents/oldata/DATA/mydata.csv")例如: read.csv("../olddata/DATA/mydata.csv")read.csv("D:/Documents/oldata/DATA/mydata.csv")相同

This is the best way for me to code scripts, no matter what computer you are using.这是我编写脚本的最佳方式,无论您使用的是什么计算机。

I realize that this is an old thread, but I had a similar problem with needing to set the working directory and couldn't get any of the solutions to work for me.我意识到这是一个旧线程,但我遇到了类似的问题,需要设置工作目录并且无法获得任何适合我的解决方案。 Here's what did work, in case anyone else stumbles across this later on:这是有效的方法,以防其他人以后偶然发现:

# SET WORKING DIRECTORY TO CURRENT DIRECTORY:
system("pwd=`pwd`; $pwd 2> dummyfile.txt")
dir <- fread("dummyfile.txt")
n<- colnames(dir)[2]
n2 <- substr(n, 1, nchar(n)-1)
setwd(n2)

It's a bit convoluted, but basically this uses system commands to get the working directory and save it to dummyfile.txt, then R reads that file using data.table::fread.这有点复杂,但基本上这使用系统命令获取工作目录并将其保存到 dummyfile.txt,然后 R 使用 data.table::fread 读取该文件。 The rest is just cleaning up what got printed to the file so that I'm left with just the directory path.剩下的就是清理打印到文件中的内容,这样我就只剩下目录路径了。

I needed to run R on a cluster, so there was no way to know what directory I'd end up in (jobs get assigned a number and a compute node).我需要在集群上运行 R,因此无法知道我最终会进入哪个目录(作业被分配了一个编号和一个计算节点)。 This did the trick for me.这对我有用。

This answer can help:这个答案可以帮助:

script.dir <- dirname(sys.frame(1)$ofile)

Note: script must be sourced in order to return correct path注意:必须获取脚本才能返回正确的路径

I found it in: https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-我在以下位置找到它:https: //support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-

The BumbleBee´s answer (with parent.frame instead sys.frame) didn´t work to me, I always get an error. BumbleBee 的回答(使用 parent.frame 而不是 sys.frame)对我不起作用,我总是会出错。

The solution解决方案

dirname(parent.frame(2)$ofile)

not working for me.不适合我。

I'm using a brute force algorithm, but works:我正在使用蛮力算法,但有效:

File <- "filename"
Files <- list.files(path=file.path("~"),recursive=T,include.dirs=T)
Path.file <- names(unlist(sapply(Files,grep,pattern=File))[1])
Dir.wd <- dirname(Path.file)

More easy when searching a directory:搜索目录时更容易:

Dirname <- "subdir_name"
Dirs <- list.dirs(path=file.path("~"),recursive=T)
dir_wd <- names(unlist(sapply(Dirs,grep,pattern=Dirname))[1])

If you work on Linux you can try this:如果你在 Linux 上工作,你可以试试这个:

setwd(system("pwd", intern = T) )

It works for me.这个对我有用。

The here package provides the here() function, which returns your project root directory based on some heuristics. here包提供了here()函数,它会根据一些启发式方法返回您的项目根目录。

Not the perfect solution, since it doesn't find the location of the script, but it suffices for some purposes so I thought I'd put it here.不是完美的解决方案,因为它找不到脚本的位置,但它足以满足某些目的,所以我想我会把它放在这里。

I understand this is outdated, but I couldn't get the former answers to work very satisfactorily, so I wanted to contribute my method in case any one else encounters the same error mentioned in the comments to BumbleBee's answer.我知道这已经过时了,但我无法让以前的答案非常令人满意地工作,所以我想贡献我的方法,以防其他人遇到与 BumbleBee 的答案评论中提到的相同错误。

Mine is based on a simple system command.我的是基于一个简单的系统命令。 All you feed the function is the name of your script:您为函数提供的只是脚本的名称:

extractRootDir <- function(x) {
    abs <- suppressWarnings(system(paste("find ./ -name",x), wait=T, intern=T, ignore.stderr=T))[1];
    path <- paste("~",substr(abs, 3, length(strsplit(abs,"")[[1]])),sep="");
    ret <- gsub(x, "", path);
    return(ret);
}

setwd(extractRootDir("myScript.R"));

The output from the function would look like "/Users/you/Path/To/Script" .该函数的输出看起来像"/Users/you/Path/To/Script" Hope this helps anyone else who may have gotten stuck.希望这可以帮助其他可能被卡住的人。

setwd(this.path::here())

works both for sourced and "active" scripts.适用于来源脚本和“活动”脚本。

I was just looking for a solution to this problem, came to this page.我只是在寻找这个问题的解决方案,来到这个页面。 I know its dated but the previous solutions where unsatisfying or didn't work for me.我知道它过时了,但以前的解决方案对我来说不令人满意或不起作用。 Here is my work around if interested.如果有兴趣,这是我的解决方法。

filename = "your_file.R"
filepath = file.choose()  # browse and select your_file.R in the window
dir = substr(filepath, 1, nchar(filepath)-nchar(filename))
setwd(dir)

I feel like a mocking bird, but I'm going to say it: I know this post is old, but...我觉得自己像一只反舌鸟,但我要说的是:我知道这篇文章很旧,但是......

I just recently learned you cannot call the api when running the script from Task Scheduler and a.bat file.我最近才知道从任务计划程序和 a.bat 文件运行脚本时无法调用 api。 I learned this the hard way.我经过惨痛的教训才学到这个。 Thought those of you who were using any of the rstudioapi:: methods might like to know that.我想那些使用rstudioapi::方法的人可能想知道这一点。 We run lots of script this way overnight.我们一夜之间以这种方式运行了很多脚本。 Just recently changed our path to include the api called so we could "dynamically" set the working directory.最近刚刚更改了我们的路径以包含调用的 api,因此我们可以“动态”设置工作目录。 Then, when the first one we tried with failed when triggered from Task Scheduler, investigation brought that information about.然后,当我们尝试的第一个失败时从任务计划程序触发时,调查提供了有关的信息。

This is the actual code that brought this issue to light:这是揭示此问题的实际代码:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) setwd(目录名(rstudioapi::getActiveDocumentContext()$path))

Works beautifully if you're running the script though!不过,如果您正在运行脚本,效果会很好!

Just adding my two cents as I know people still pull these threads up, thought it might be helpful.只需添加我的两分钱,因为我知道人们仍然会拉起这些线程,认为这可能会有所帮助。

In case you use UTF-8 encoding:如果您使用 UTF-8 编码:

path <- rstudioapi::getActiveDocumentContext()$path
Encoding(path) <- "UTF-8"
setwd(dirname(path))

You need to install the package rstudioapi if you haven't done it yet.如果您还没有安装包 rstudioapi,则需要安装它。

Most GUIs assume that if you are in a directory and "open", double-click, or otherwise attempt to execute an.R file, that the directory in which it resides will be the working directory unless otherwise specified.大多数 GUI 假设如果您在一个目录中并“打开”、双击或以其他方式尝试执行一个 .R 文件,除非另有说明,否则它所在的目录将是工作目录。 The Mac GUI provides a method to change that default behavior which is changeable in the Startup panel of Preferences that you set in a running session and become effective at the next "startup". Mac GUI 提供了一种更改默认行为的方法,该默认行为可在您在运行会话中设置的首选项的启动面板中更改,并在下一次“启动”时生效。 You should be also looking at:你还应该看看:

?Startup

The RStudio documentation says: RStudio 文档说:

"When launched through a file association, RStudio automatically sets the working directory to the directory of the opened file." “通过文件关联启动时,RStudio 会自动将工作目录设置为打开文件的目录。” The default setup is for RStudio to be register as a handler for.R files, although there is also mention of ability to set a default "association" with RStudio for.Rdata and.R extensions.默认设置是将 RStudio 注册为 .R 文件的处理程序,尽管也提到了为 .Rdata 和 .R 扩展设置与 RStudio 的默认“关联”的能力。 Whether having 'handler' status and 'association' status are the same on Linux, I cannot tell.我不知道在 Linux 上具有“处理程序”状态和“关联”状态是否相同。

http://www.rstudio.com/ide/docs/using/workspaces http://www.rstudio.com/ide/docs/using/workspaces

dirname(parent.frame(2)$ofile)  

doesn't work for me either, but the following (as suggested in https://stackoverflow.com/a/35842176/992088 ) works for me in ubuntu 14.04对我也不起作用,但以下内容(如https://stackoverflow.com/a/35842176/992088中所建议)在 ubuntu 14.04 中对我有用

dirname(rstudioapi::getActiveDocumentContext()$path)

Here is another way to do it:这是另一种方法:

set2 <- function(name=NULL) {
  wd <- rstudioapi::getSourceEditorContext()$path
  if (!is.null(name)) {
    if (substr(name, nchar(name) - 1, nchar(name)) != '.R') 
      name <- paste0(name, '.R')
  }
  else {
    name <- stringr::word(wd, -1, sep='/')
  }
  wd <- gsub(wd, pattern=paste0('/', name), replacement = '')
  no_print <- eval(expr=setwd(wd), envir = .GlobalEnv)
}
set2()

I am working out some tutorials in R. Each R code is contained in a specific folder.我正在用R编写一些教程。每个R代码都包含在一个特定的文件夹中。 There are data files and other files in there.那里有数据文件和其他文件。 I want to open the .r file and source it such that I do not have to change the working directory in Rstudio as shown below:我想打开.r文件并将其来源,这样我就不必更改Rstudio中的工作目录,如下所示:

在此处输入图片说明

Is there a way to specify my working directory automatically in R.有没有一种方法可以在R中自动指定我的工作目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM