Is there a way of configuring a script to run using the current working directory of the console instead of the directory in which it is saved?
Would including the line
current_wd <- getwd() in the script help in your case?
How are you calling the script ? by a source() in the console ?
getwd() in the script returns the directory path in which the Rmd script is saved. I'm executing the script by ctlAltR in Rstudio. Rstudio objects to and apparently restricts setwd() to the chunk in which it executes.
My directory structure is ./scripts containing *.Rmd and executables *.sh, etc ;
./dataForFirstEpisode/ containing *.csv, *.RData, etc ; ./dataForIthEpisode mirroring the files in episode 1. FWIW, I got around my problem by inserting symbolic links to the Rmd files in each episode. It's not ideal.
By any chance, are you D Romano at UWisc River Falls?
What you describe is specific to rmarkdown, and wouldnt be the experience for a
'pure' r script. I believe its more of an rmarkdown/knitr issue than an Rstudio issue.
I found this blog, suggesting the use of the here package :
However, when you knit the document (or spin, or compose notebook… any of the aliases to
knitr::knit()and associated functions), the document is evaluated in its own environment. From the perspective of knitr, the base directory is the directory in which you saved the .R, .md, or .Rmd document. Assuming you saved your RMarkdown script in
R/, then knitting that document with the same code as above
I'm wondering whether something like using a normal rscript (that knows the getwd() from the console when its called) and using it to itself knit the markdown doc, passing in the directory to use as a parameter would be a way to go ?
I'm afraid you're at a disadvantage since there are so many more D Romanos than there are sdutkys, but I'm the older of the two who learned to fish from the mortal foe of Japanese beetles
I found that there is way of reading the current directory from within the .Rmd file:
--- title: "Untitled" author: "Me" date: "2/24/2020" output: html_document params: wd: !r getwd() ---
This creates a
params list visible to the new R session, and the path is the value of
params$wd. Does that work for you, Steve (@sdutky)?
P.P.S. I was wrong -- it's still reading from where the .Rmd sits.
Another possibility, along the lines @nirgrahamuk suggested: One script with
cwd <- getwd() saveRDS(cwd, '[path to .Rmd directory]/wd')
params: wd: !r readRDS('wd')
in the .Rmd file. That worked for me. (I wasn't sure how to run the .Rmd file from within a script, so didn't do that.)
setting params in the Rmd header block seems like the most elegant approach. I will see how it works.
It occurs to me that because I generally fetch my data from a url and not from episodic directories this never was a problem.
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.