【问题标题】:"Error in file" instead of "Error in eval" when specifying output file in knit2html在 knit2html 中指定输出文件时,“文件错误”而不是“eval 错误”
【发布时间】:2014-04-07 16:02:22
【问题描述】:

我正在从一个名为“template.Rmd”的 Rmd 文件中制作多个 html 报告。 使用函数 knit2html() 时,会出现误导性错误消息“无法打开连接”,而实际上该错误是由于代码错误,例如缺少变量。下面我通过一个小例子来说明:

Template.Rmd 包含这个内联 R 代码:

`r missing_variable`

当我不指定输出文件时,我会收到一条有用的错误消息

> knit2html("docs/template.Rmd")
Quitting from lines 2-4 (docs/template.Rmd) 
Error in eval(expr, envir, enclos) : object 'missing_variable' not found

当我指定输出文件时,我收到一条误导性的错误消息

> knit2html("docs/template.Rmd", "docs/template.html")
Warning in file(file, ifelse(append, "a", "w")) :
cannot open file 'docs/template.html': No such file or directory
Error in file(file, ifelse(append, "a", "w")) : 
cannot open the connection

这是与knitr相关的问题吗?

【问题讨论】:

    标签: r knitr r-markdown


    【解决方案1】:

    我无法在 CRAN 上使用最新版本的 R 和 knitr 重现您的问题,但在大多数情况下,您不需要指定 output 参数,强烈不推荐使用包含目录名称的输出路径,例如docs/template.html(请参阅?knit 中的注释部分)。在您的情况下,只需将工作目录切换到 docs 并运行 knit2html(),例如

    setwd('docs')
    knit2html('template.Rmd')  # generates template.html
    

    【讨论】:

    • 我想从一个模板生成多个输出文件。每个输出文件需要不同的名称。 [Hadley]() 和您自己建议避免在脚本中使用 setwd()。这就是为什么我尽量避免使用它。目前我正在使用setwd("docs"); tryCatch(knit("template.Rnw"), finally= setwd(project_dir))
    • 为了澄清,我们建议不要使用setwd() inside Rmd 文档,或before knit(),而不是避免使用setwd()完全地。当然,在很多合法的情况下,setwd() 是必要且有用的。
    • 感谢您的回复...?knit 中的注释部分说“强烈建议在当前工作目录中”。我真的不明白为什么knit2html() 的输出路径不应该包含目录名,但我感觉一定有一个强有力的理由。很遗憾,您无法重现我在问题中提到的错误。 ...要从一个 .Rmd 模板创建多个 html 报告,然后我将在 /docs 目录中的 setwd() 并在每个 knit2html() 之后使用 file.copy() 重命名每个输出文件。
    • 原因是外部依赖。例如,一个 HTML 文件可能依赖于外部图像(默认在当前工作目录下的 figures/ 目录下,例如 ~/wd/);如果将输出的 HTML 文件写入docs/foo.html,将找不到图像<img src='figures/bar.png' />,因为HTML 页面会查找~/wd/docs/figures/bar.png,但图像实际上是~/foo/figures/bar.png。 CSS、JS、缓存文件等也是一样。如果你file.copy(),你需要考虑这些依赖关系,虽然markdown默认会base64编码图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 2015-02-12
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2011-09-10
    相关资源
    最近更新 更多