R命令用于将工作目录设置为Rstudio中的源文件位置 [英] R command for setting working directory to source file location in Rstudio

查看:34
本文介绍了R命令用于将工作目录设置为Rstudio中的源文件位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 R 编写一些教程.每个 R 代码都包含在一个特定的文件夹中.里面有数据文件和其他文件.我想打开 .r 文件并获取它,这样我就不必更改 Rstudio 中的工作目录,如下所示:

I am working out some tutorials in R. Each R code is contained in a specific folder. 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 中自动指定我的工作目录.

Is there a way to specify my working directory automatically in R.

推荐答案

要获取源脚本的位置,您可以使用 utils::getSrcDirectoryutils::getSrcFilename.因此,可以通过以下方式将工作目录更改为当前文件的工作目录:

To get the location of a script being sourced, you can use utils::getSrcDirectory or utils::getSrcFilename. So changing the working directory to that of the current file can be done with:

setwd(getSrcDirectory()[1])

如果您运行代码而不是源代码,这在 RStudio 中不起作用.为此,您需要使用 rstudioapi::getActiveDocumentContext.

This does not work in RStudio if you Run the code rather than Sourceing it. For that, you need to use rstudioapi::getActiveDocumentContext.

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

当然,第二种解决方案要求您使用 RStudio 作为 IDE.

This second solution requires that you are using RStudio as your IDE, of course.

这篇关于R命令用于将工作目录设置为Rstudio中的源文件位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆