1

I try to save a variable to a relative path. The R code runs without a problem in RStudio, but as soon as I compile the RMarkdown file i get a reproducible error (only if the destination path is relative).

This is my RMarkdown file:

---
title: "Untitled"
output: html_document
---

```{r test}
x<-"test"
save(x,file="./raw_data/test.r")
```

This is the resulting error:

processing file: Untitled.Rmd

Quitting from lines 7-9 (Untitled.Rmd) 
Error in gzfile(file, "wb") : cannot open the connection
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> save -> gzfile
Execution halted

Is this a bug / does knitr not support relative directory paths?

Thanks

  • Does the error occur if you use a tilde ~ instead of a period in the path name? – lawyeR Dec 28 '16 at 12:50
  • ~/ instead of ./ is incorrect, this points to the home directory. I have figured out that I can avoid the error when I use "../" for relative subdirectories in Knitr. This is equivalent to "./" in Rstudio. Unfortunately, this results in an error in the R code. So Knitr and R seem to evaluate this differently, which means that I have to adapt the R code for Knitr which defies the purpose of literate programming a bit. – Andreas Moor Dec 28 '16 at 13:55
  • Add a chunk that prints the result of `getwd()`. You'll likely see something different than what you were expecting. You can fix this by using `setwd()` early in the document so that the working dir is what you expect it to be. – user2554330 Dec 28 '16 at 23:55
  • So according to the [package author](https://groups.google.com/forum/#!topic/knitr/knM0VWoexT0), knitr uses the location of the Rmd file as working directory and does not take into account the RStudio working dir. setwd() does not work in Knitr (see discussion [here](http://stackoverflow.com/questions/20060518/in-rstudio-rmarkdown-how-to-setwd), I now use their recommendation ` ```{r setup} opts_chunk$set(root.dir = '/tmp') ``` `. This works for all subsequent Knitr R code chunks. – Andreas Moor Dec 29 '16 at 07:14
  • in the next version it will be available : https://www.rstudio.com/products/rstudio/download/preview-release-notes/ – s.brunel Dec 29 '16 at 12:19

0 Answers0