0

Using the Knit button from RStudio works beautifully for me when working with simple files, automatically generates the Rmd files and then the PDF. Now I am working on a larger project where I've split the directories to

MainProjectDir/

MainProjectDir/Code/

MainProjectDir/DataRaw/

MainProjectDir/DataWork/

getwd() gives me the MainProjectDir path. The .r files in the Code directory call each other and also load and save data from/to the Data directories by using relative paths from the MainProjectDir path.

Now, when using the Knit button for a .r file in the Code directory I get connection error:

Error in file(filename, "r", encoding=encoding) : cannot open the connection

After reading a few responses here and looking at Yihui's page I tried setting the root.dir option in the knitr package with

knitr::opts_knit$set(root.dir="..")

in the console before pressing the Knit button in RStudio. Still I get same error. Tried also an absolute path version of the path. What am I doing wrong?

claudiu
  • 60
  • 8
  • Have you tried to use the `rmarkdown::render` function? – YCR Aug 23 '16 at 08:47
  • I'm using the File/Knit menu command, letting RStudio do the invocations to pandoc/knitr. Works well on simple directories structure that's why I'm trying to find a way to describe the relative paths correctly. What is the flow you propose? – claudiu Aug 23 '16 at 08:58
  • You have another script in which you use the function rmarkdown::render. It allows a better control of your environment. It's best to clean your global environment with `rm(list = ls())` before, tough. – YCR Aug 23 '16 at 09:19
  • before I get on that path, why is knitr::opts_knit$set(root.dir="..") not working? – claudiu Aug 23 '16 at 09:28
  • You know you can put in your script print(getwd()) to know where is the script executed? – YCR Aug 23 '16 at 09:32
  • Tried, the .r file is executed in MainProjectDir above, as given also by getwd() outside of script. the knit error shows it tries to write the .Rmd file in the Code directory, where the .r file resides. – claudiu Aug 23 '16 at 09:39
  • When you use the `knit` **button**, RStudio creates a brand new R session to knit in - so anything you previously entered in the console doesn't matter. A very good solution would be to put `knitr::opts_knit$set(root.dir="")` in your first code chunk. You may even be able to get away with `knitr::opts_knit$set(root.dir="..")` in your document (if the main directory is one level above where you are knitting). – Gregor Thomas Aug 23 '16 at 19:40
  • I'm going to guess it's this common pitfall... The working directory set by `knitr::opts_knit$set(root.dir = "..")` is not effective until the next code block. The block with `knitr::opts_knit$set(root.dir = "..")` should not read/write any files. That should happen in the next block. http://rpubs.com/tjmahr/knitr-root-dir – TJ Mahr Aug 23 '16 at 19:46
  • Following Gregor's and Mahr's suggestions I created a _knit_invoke.r_ file with just the `knitr::opts_knit$set(root.dir = "..")` and `source("main.r")` commands and used the **knit button** on it but it still didn't work. Got same error in Rmarkdown window while creating _..../Code/knit_invoke.spin.Rmd_. I guess RStudio button does not call knitr directly, seems the Rmd creation phase is the problem. Still keeping my workaround for now, not pretty but works.. – claudiu Aug 24 '16 at 19:35

3 Answers3

0

Found this workaround for the problem on github discussion thread, added to R code and works:

if (basename(getwd())=="Code") setwd(normalizePath(".."))

Posting this for anyone looking for a quick solution but if someone can explain what was wrong with

knitr::opts_knit$set(root.dir="..")

and how to fix it please post and I'll accept his answer.

claudiu
  • 60
  • 8
0

Not sure if this will solve all your troubles, but have you had a look at Dean Attali's ezknitr package? It gives you more flexibility with directories.

Peter K
  • 706
  • 5
  • 8
  • Looked at it now, based on the documentation this package should indeed allow the directory structure I'm using. Still, for now I'd like to keep the convenience of working with the RStudio knit button and original R files instead of Rmd so keeping the ugly workaround found. See the comment I wrote to Gregor's suggestion above. If only I could remove the setwd()... – claudiu Aug 24 '16 at 19:44
0

When using a nested file structure with an R project it is important to be aware of the following (as noted in the comments above)

  • When opening an project in RStudio, the default working directory is set to the folder containing the .Rproj file (ie. MainProjectDir/).
  • During knitting Rstudio opens a brand new R session and the default working directory is set to the folder containing the .Rmd file (ie. MainProjectDir/Code/).
  • The default working directory can be changed using knitr::opts_knit$set(root.dir=".."), but the change is not effective until the following code chunk. So don't load data until the next code chunk.
  • You can use the command knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file()), to set the working directory back to the folder containing the .Rproj file during knitting.

So at a minimum use the following:

---
title: "Title"
author: 'Author'
date: "`r Sys.Date()`"
output: html_document
---

First chunk

```{r setup, include=TRUE}

print(getwd())
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
print(getwd())

```

Second chunk

```{r load data}

print(getwd())

read.csv(file = "DataRaw/exampledata.csv")

```

See also Setting work directory in knitr using opts_chunk$set(root.dir = ...) doesn't work, Automatically finding the path of current R project in R Studio and https://support.rstudio.com/hc/en-us/community/posts/220826588-Working-directory-in-R-Notebooks.

JWilliman
  • 3,558
  • 32
  • 36