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

标签 r markdown r-markdown

我在 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/

相关文章:

r - R 和 scikit-learn 在逻辑回归分类任务中的比较

重新上传相同的文件 Shiny R

python - 如何使用 Material mkdocs 包突出显示代码块?

r - 仅在 R Markdown 中使用 ggplot2 时出现 "Faceting variables must have at least one value"错误;这是什么意思?

html - Markdown : go to a particular line during the knitting proccess if condition occurs

r - 聚合嵌套列表对象中不同列表的相似列

r - ggplot2/geom_line 问题 - 错误地联合绘制了子集数据集

r - 如何在 R markdown 中乱序显示变量?

visual-studio-code - 目录中的 MarkdownTOC 在更新和插入时用 auto 替换换行符

r - 在 Rmarkdown 文档中使用 R 代码添加引用