如何设置每个块的编织块输出宽度? [英] How to set knitr chunk output width on a per chunk basis?

查看:78
本文介绍了如何设置每个块的编织块输出宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

针织衫是否具有允许按每个块设置R的width选项的选项?

Does knitr have an option that allows one to set R's width option on a per chunk basis?

如果不是,是否有充分的理由(即,基于 knitr 模型的一些基本限制)?

If not, is there a good reason (i.e. one rooted in some fundamental limitation of the knitr model) that it does not?

要显示我的期望,这里有一个手动执行的挂钩函数,可以基本上执行我想要的操作. (尽管我不太喜欢它,(a)因为丑陋,依赖于将变量.width分配给全局环境,以及(b)因为它不是开箱即用"的提供选项.例如fig.widthout.width等)

To show what I'm wishing for, here is a hand-rolled hook function that does basically what I want. (I don't really like it though, (a) because it is ugly, relying on assignment of the variable .width into the global environment, and (b) because it's not available "out of the box" as a supplied option like fig.width, out.width, et al.)

\documentclass[preview=true,width=3mm]{standalone}

\begin{document}

<<setup, include=FALSE, cache=FALSE>>=
options(width=60)

knit_hooks$set(width = function(before, options, envir) {
if(before) {
    .width <<- options(width=options$width) ## Set width and save 'old' value
} else {
    options(.width)}                        ## Restore width's 'old' value
})

@

First chunk uses default width
<<A>>=
c("aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee", "fffff", "ggggg", "hhhhh")
@

Second chunk uses narrower supplied width, but then resets width to
pre-existing value \dots
<<B, width=20>>=
c("aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee", "fffff", "ggggg", "hhhhh")
@

\noindent \dots as shown by results of the third chunk
<<C>>=
c("aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee", "fffff", "ggggg", "hhhhh")
@

\end{document}

推荐答案

尽管不是整体问题的解决方案,但您对代码的第一点抱怨是它使.width变量影响了全局环境.可以使用local()作为 closure 机制来解决此问题,该机制封装了变量,以便在全局var空间中不会发生冲突.

Though not a solution to the overall question, your first complaint with your code is that it gums up the global environment with your .width variable. This can be resolved using local() as a closure mechanism, encapsulating your variable so that you get no collisions in global var space.

因此,如果您将knit_hooks$set通话替换为:

So, if you replace your knit_hooks$set call with:

knit_hooks$set(width=local({
    .width <- 0
    function(before, options, envir) {
        if (before) .width <<- options(width=options$width)
        else options(.width)
    }
}))

它产生相同的结果,而没有强迫.width进入全局环境的问题.上面的其余代码可以像以前一样工作,并具有相同的输出.

it produces the same results without the problem of forcing .width into the global environment. The rest of your code above works as before with identical output.

更多内容可以在help(local)高级R编程(Hadley Wickham)中阅读,以及有很多例子,例如@JeroenOoms的 OpenCPU .

More can be read at help(local), in Advanced R Programming (Hadley Wickham), and there are several examples of it in the wild, such as @JeroenOoms' OpenCPU.

这篇关于如何设置每个块的编织块输出宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆