更新时间:2023-09-17 15:36:46
要获取源脚本的位置,可以使用utils::getSrcDirectory
或utils::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])
如果您运行代码而不是 Source 对其进行编码,则这在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.