2

I have a Rstudio project set up with the .Rprofile containing

library(tidyverse)
library(knitr)
knitr::opts_chunk$set(cache.path='cache/', fig.path='figures/')

I separately have a .Rmd file in a subdirectory when I render into a html. However, it appears that .Rprofile is not sourced at all until I directly source it using source(here('.Rprofile')). I do know that it is sourced properly in the console, and I'd like the knitr render process to source it to (without me directly doing it). What is going on? Thanks!

Phil
  • 7,287
  • 3
  • 36
  • 66
TJ Singh
  • 61
  • 2
  • Maybe you ran in the same issue as https://stackoverflow.com/questions/50686292/rprofile-not-sourced – stefan Sep 03 '20 at 18:43
  • I did see that issue and added some newlines and changed the User option that appends the newline and it still didn't render. – TJ Singh Sep 03 '20 at 18:54
  • Hm. Works fine when I add your chunk to my .Rprofile and knit a simple rmd. – stefan Sep 03 '20 at 19:06
  • Is your Rmd in the same directory as the .Rprofile? I have it in a subdirectory in the same project. – TJ Singh Sep 03 '20 at 19:49
  • Okay. I first tried on my default .Rprofile. So. In that case everything is fine. However, when I put your chunk in an .Rprofile in the project dir it only gets loaded when it is in the same dir as the rmd. Hm. So at least I could replicate the problem. (; – stefan Sep 03 '20 at 20:05
  • haha at least I'm not going crazy! I thought .Rprofiles were automatically sourced wherever in the project dir but maybe that's not the case? – TJ Singh Sep 03 '20 at 20:12
  • (: The issue is probably that by default the working dir of a Rmd document is the dir where the rmd is located. See https://bookdown.org/yihui/rmarkdown-cookbook/working-directory.html . When setting the default wd as the project dir in the Rstudio options the .Rprofile is found and executed. But not sure wether this is an option for you. – stefan Sep 03 '20 at 20:28
  • I changed to knitr directory to the project directory and it seems to run. However, it doesn't seem to change the knitr options... `print(knitr::opts_chunk$get('cache.path'))` gave the default. I think I am going to give up on using .Rprofile to change knitr options and do it as a separate source script... – TJ Singh Sep 03 '20 at 20:51

1 Answers1

1

When you click the knit button in Rstudio, it launches a separate R session to compile the document (source) and this process occurs in the directory the .Rmd file is located. If that directory is not your project root (i.e. where your .Rprofile is), the .Rprofile is not being properly sourced. To source it, add this at the top of your .Rmd:

source("../.Rprofile", chdir = TRUE)
Anna Nevison
  • 2,709
  • 6
  • 21