使用 knitr 时如何打印到控制台?

How can I print to the console when using knitr?

我正在尝试打印到控制台(或输出 window)以进行调试。例如:

\documentclass{article}

\begin{document}

<<foo>>=
print(getwd())
message(getwd())
message("ERROR:")
cat(getwd(), file=stderr())
not_a_command() # Does not throw an error?
stop("Why doesn't this throw an error?")
@


\end{document}

我在输出 PDF 中得到了结果,但我的问题是我有一个未完成的脚本(因此没有要检查的输出 PDF),我正在尝试了解原因。如果编织没有成功完成,似乎也没有日志文件输出。

我正在使用 knitr 1.13 和 Rstudio 0.99.896。

编辑:如果我更改为 Sweave,上面的代码将正确输出(并中断),所以这让我认为这是一个 knitr 问题。

这个问题有几个方面 – 部分 XY problem。核心问题是(正如我所读):

How can I see what's wrong if knitr fails and doesn't produce an output file?

  • 在PDF输出的情况下,经常出现错误后编译输出PDF失败,但仍然存在中间TEX文件。打开此文件可能会显示错误消息。
  • ,您可以在控制台中逐行(或逐块)运行块中的代码。但是,这可能不会重现所有问题,尤其是与工作目录或环境相关的问题。
  • capture.output可用于将调试信息打印到外部文件。
  • 最后(与我之前的评论相反),它 可以打印 RStudio 的进度 window(或者不管它叫什么):消息 from hooks 将打印在进度 window 上。基本上,消息必须来自 knitr 本身,而不是来自 knitr 计算的代码。

How can I print debug information on the progress window in RStudio?

以下示例在每个 debug = TRUE 块之后打印环境中的所有对象:

\documentclass{article}

\begin{document}

<<>>=
knitr::knit_hooks$set(debug = function(before, options, envir) {
  if (!before) {
    message(
      paste(names(envir), as.list(envir),
            sep = " = ", collapse = "\n"))
  }
})
@

<<debug = TRUE>>=
a <- 5
foo <- "bar"
@

\end{document}

进度window显示:

当然,对于包含更多或更大对象的文档,应调整挂钩以选择性地打印(部分)对象。