R Markdown 找不到文件但执行块有效

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

我在使用 r markdown 和读取 txt 文件时有一个奇怪的行为...仅在 windows 7 机器上。我的 Mac 没问题,还没有在 windows 8 上检查过。

我有一个基本的 r markdown 文档

---
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)
```

如果我在最后一个块中设置 eval=FALSE,则会创建 html 并使用我的 test.txt 文件获取列表。如果我设置 eval=TRUE,我会收到一条错误消息,指出找不到该文件:

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

如果我将所有内容都放在一个块中,则会创建 html。

有人知道问题出在哪里吗?

编辑: 也许我不够清楚。我知道 eval=TRUE 和 FALSE 之间的区别,但我不知道在降价中测试某些东西的方法,如果有错误消息,但在块中一切正常。

所以,为了更清楚:

作品:

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

不工作:

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

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

You cannot use setwd in knitr, and you shouldn’t use it in your R code anyway. 您需要专门使用 相对路径

特别是,setwd 在其当前块之外没有任何影响——其他块将在文档路径中进行评估,而不是在设置的路径中。

一般来说,setwd 只应由用户在交互式会话中使用,或者在您的项目配置文件(本地 .Rprofile 文件)中设置项目目录。 It has no place in scripts.

setwd 最直接的等价物是使用 knitr 选项 root.dir:

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