编织到 HTML 时找不到本地函数
Local function not found when knitting to HTML
我看到有人问过与此类似的问题,但没有确定的答案...我正在尝试将 rmd 文件编织到 html 并使用我在 .R 中编写的函数文件。我收到一条错误消息,提示无法找到该函数等。
另外请注意,当我 运行 调用该函数的代码块时,它会起作用。只是编织时出错
这是因为您在 Rstudio
中使用编织按钮创建一个新会话,然后从控制台执行 rmarkdown::render
, in order to use locally defined function you have to call 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 的评论:
最好将您的文件 source
放入 rmd 本身,因为 Rmarkdown 的主要目标是可重复的研究。
```{r setup, include=FALSE}
.
.
.
source("path/to/file.R")
```
我看到有人问过与此类似的问题,但没有确定的答案...我正在尝试将 rmd 文件编织到 html 并使用我在 .R 中编写的函数文件。我收到一条错误消息,提示无法找到该函数等。
另外请注意,当我 运行 调用该函数的代码块时,它会起作用。只是编织时出错
这是因为您在 Rstudio
中使用编织按钮创建一个新会话,然后从控制台执行 rmarkdown::render
, in order to use locally defined function you have to call 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 的评论:
最好将您的文件 source
放入 rmd 本身,因为 Rmarkdown 的主要目标是可重复的研究。
```{r setup, include=FALSE}
.
.
.
source("path/to/file.R")
```