【问题标题】:Local function not found when knitting to HTML编织到 HTML 时找不到本地函数
【发布时间】:2021-02-08 03:59:39
【问题描述】:

我看到有人问了与此类似的问题,但没有确定的答案...我正在尝试将 rmd 文件编织到 html 并使用我在 .R 文件中编写的函数。我收到一条错误消息,提示找不到函数等。

另外请注意,当我运行调用该函数的代码块时,它可以工作。只是编织时出错。

【问题讨论】:

  • 你的函数是在rmd文件本身中定义的吗?当您编织 rmd 文件时,它会在新的 R 会话中运行。编织文档所需的一切都需要包含在文档本身中。如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。

标签: r knitr


【解决方案1】:

这是因为您使用Rstudio 中的 knit 按钮创建一个新会话然后执行 rmarkdown::render,为了使用本地定义的函数,您必须从控制台调用 rmarkdown::render

注意:这将阻塞控制台,直到 .Rmd 文件被渲染。

my.envir <- new.env(parent=baseenv())
local({
  f <- function() { ... }
  #...
}, my.envir)
# OR source your file directly into my.envir
source("ur.file.R", local = my.envir)
rmarkdown::render(input, # path to the .Rmd file
   output_format = "html_document", # output type if not set it'll use the first one found in the yaml header
   output_file = NULL, # name of the output file by default it will be the 
       # name of the .Rmd with the extension changed
   clean = TRUE,  # set to FALSE if you want to keep intermediary files
   envir = my.envir, # this where the magic happens
       # if you don't want to modify the global env you can create your own environment and add the function to it
   quiet = FALSE # set to TRUE if you want to suppress the output
)

编辑@KonardRudolph 的 cmets:

最好将您的文件source 放入 rmd 本身,因为 Rmarkdown 的主要目标是可重复研究。

```{r setup, include=FALSE}
.
.
.
source("path/to/file.R")
```

【讨论】:

  • RStudio 的行为非常刻意,强烈建议不要使用您建议的解决方案。
  • @KonradRudolph 是否因为它暴露了全局环境而气馁,如果是这样我改变了环境参数
  • 问题在于它使编织依赖于一些外部状态,因此无法重现。如果您使用不同的环境,这也是正确的。它确实需要一个 clean 环境(理想情况下是一个完全干净的 session,以防止其他副作用,例如不同的加载包)。
  • 他可以直接source rmd tbh里面的文件
猜你喜欢
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 1970-01-01
相关资源
最近更新 更多