rstudio / rstudioapi

Safely access RStudio's API (when available)
http://rstudio.github.io/rstudioapi
Other
165 stars 35 forks source link

setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) can not be evaluated locally #268

Closed micwij closed 1 year ago

micwij commented 1 year ago

Hi,

I commonly used the command setwd(dirname(rstudioapi::getActiveDocumentContext()$path)), to set the working directory to the source file location in most of my .R scripts. I now just wanted to run several smaller scripts by sourcing them from a different script, but couldn't get it it to evaluate the command locally even when setting local = T in source(). Instead the working directory is always set to the executing file's location. Is there a way to circumvent this or did I do something wrong?

Thanks a lot in advance!

Best, Micha

kevinushey commented 1 year ago

getActiveDocumentContext() always returns the path of the document currently open in the RStudio IDE; not the one that might be executed currently (e.g. via source()).

Unfortunately, there isn't a general mechanism for getting the path to the "current" R script being executed, but there are some heuristics (for example, see examples at https://stackoverflow.com/questions/47044068/get-the-path-of-current-script).