knitr 书,p。 118,\S 12.3.5, 有一个例子说明如何通过修改抑制长输出
输出块钩子(Hook),但它根本不是通用的,因为它对所有块都是全局的。

我试图概括这一点,以允许块选项 output.lines ,如果为 NULL,则没有
效果,否则仅选择并打印前 output.lines 行。不过这个版本
我尝试的时候似乎没有效果,我不知道如何说出原因。

更一般地说,我认为这足够有用,可以包含在 knitr 中,如果有的话会更好
可以指定一系列行,例如 output.lines=3:15 ,就像 echo= 一样。

# get the default output hook
hook_output <- knit_hooks$get("output")

knit_hooks$set(output = function(x, options) {
    lines <- options$output.lines
    if (is.null(lines)) {
        hook_output(x, options)  # pass to default hook
    }
    else {
        x <- unlist(stringr::str_split(x, "\n"))
        if (length(x) > lines) {
        # truncate the output, but add ....
        x <- c(head(x, lines), "...\n")
        }
        # paste these lines together
        x <- paste(x, collapse = "\n")
        hook_output(x, options)
    }
})

测试用例:
<<print-painters, output.lines=8>>=
library(MASS)
painters
@

最佳答案

实际上,这个解决方案 确实 工作。我的实际测试示例有缺陷。也许其他人会发现这很有帮助。

关于hook - 通过修改默认输出钩子(Hook)选择块输出中的输出行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20982089/

10-14 18:37
查看更多