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])
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))
This second solution requires that you are using RStudio as your IDE, of course.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…