Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set knitr chunk output width on a per chunk basis?

Tags:

r

knitr

My question(s):

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

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

What I've tried:

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}

enter image description here

like image 468
Josh O'Brien Avatar asked Apr 28 '14 19:04

Josh O'Brien


Video Answer


1 Answers

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.

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)
    }
}))

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.

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.

like image 187
r2evans Avatar answered Sep 28 '22 18:09

r2evans