drmariod
drmariod

Reputation: 11762

R Markdown can't find a file but executing the chunks works

I have a strange behaviour with r markdown and reading a txt file... only on a windows 7 machine. No problems on my Mac and haven't checked it on windows 8 yet.

I have a basic r markdown document

---
title: "Untitled"
output: html_document
---
```{r global_options, message=FALSE}
setwd('E:/Falk')
list.files(pattern='test')
```

```{r global variable settings, eval=TRUE}
pg_filename <- 'test.txt' 
pg <- read.delim (pg_filename)
```

If i set the eval=FALSE in the last chunk, the html gets created and I get the list with my test.txt file. If I set eval=TRUE I get an error message, that the file can not be found:

Quitting from lines 11-13 (Preview-2b2464944991.Rmd) 
Error in file(file, "rt") : cannot open the connection
Calls: <Anonymous> ... withVisible -> eval -> eval -> read.delim -> read.table -> file

Execution halted

If I put everything in one chunk the html gets created.

Has any one an idea what the problem is?

EDIT: Maybe I was not clear enough. I know the difference between eval=TRUE and FALSE but I don't know a way of testing the something in markdown, if there are error messages, but everything works fine in the chunks.

So, to make it more clear:

WORKS:

---
title: "Untitled"
output: html_document
---
```{r}
setwd('E:/Falk')
list.files(pattern='test')
pg_filename <- 'test.txt' 
pg <- read.delim (pg_filename)
```

DOES NOT WORK:

---
title: "Untitled"
output: html_document
---
```{r}
setwd('E:/Falk')
list.files(pattern='test')
```

```{r}
pg_filename <- 'test.txt' 
pg <- read.delim (pg_filename)
```

Upvotes: 3

Views: 6332

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 546015

You cannot use setwd in knitr, and you shouldn’t use it in your R code anyway. You need to exclusively use relative paths instead.

In particular, setwd has no effect outside of its current chunk – the other chunks are going to be evaluated in the document’s path, not in the set path.

In general, setwd should only be used by the user in an interactive session, or in your project configuration file (local .Rprofile file) to set up a project directory. It has no place in scripts.

The most direct equivalent of setwd is to use the knitr option root.dir:

opts_knit$set(root.dir = 'some/dir')

Upvotes: 1

Related Questions