我在 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)
```
如果我在最后一个 block 中设置 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
如果我将所有内容都放在一个 block 中,则会创建 html。
有人知道问题出在哪里吗?
编辑: 也许我不够清楚。我知道 eval=TRUE 和 FALSE 之间的区别,但我不知道在 markdown 中测试某些东西的方法,如果有错误消息,但在 block 中一切正常。
所以,为了更清楚:
作品:
---
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
在其当前 block 之外没有任何影响——其他 block 将在文档的路径中进行评估,而不是在设置的路径中。
一般来说,setwd
应该只被用户在交互式 session 中使用,或者在你的项目配置文件(本地 .Rprofile
文件)中设置项目目录。 It has no place in scripts.
setwd
最直接的等价物是使用 knitr 选项 root.dir
:
opts_knit$set(root.dir = 'some/dir')
关于R Markdown 找不到文件但执行 block 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28580758/