【问题标题】:R Markdown can't find a file but executing the chunks worksR Markdown 找不到文件,但执行块有效
【发布时间】:2015-04-19 06:51:14
【问题描述】:

我在使用 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 之间的区别,但我不知道在 Markdown 中测试某些东西的方法,如果有错误消息,但在块中一切正常。

所以,为了更清楚:

作品:

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

【问题讨论】:

  • 您应该阅读文档:eval=FALSE 表示块只是按原样复制到输出中,而不是使用 R 评估执行 .
  • 对,我知道...这只是 mz 测试,setwd 有效,list.files 可以找到我的 test.txt 文件...否则我收到消息,那个 test.txt 确实不存在,但存在。该脚本以块的形式运行,但即使文件在那里,也不会像 eval TRUE 那样编织...不知道测试的方法...如果我将所有内容放在一个块中,该脚本也会运行!

标签: r markdown r-markdown


【解决方案1】:

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

【讨论】:

  • 感谢您指出这一点。我不在提供给其他用户的脚本中使用 ssetwd() ,正是因为这个原因,我讨厌在降价文档中使用这个解决方案。但这是我找到的唯一解决方案。感谢您的回答,我刚刚意识到,Rmd 必须在同一个文件夹中,然后相对路径才能工作。之前没有想到这一点。在我的 MAC 上,它使用 setwd() 技巧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
相关资源
最近更新 更多