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

后端 未结 2 1445
夕颜
夕颜 2021-02-07 13:20

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

相关标签:
2条回答
  • 2021-02-07 13:46

    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.

    0 讨论(0)
  • 2021-02-07 13:50

    This also answers my question. I am using Beamer and knitr to make overheads, and sometimes I make the output smaller (eg. to get an analysis of variance table in one piece without wrapping). For example, I have a default width of 50, but I can now do

    {\small 
    <<width=55>>=
      summary(my.aov)
    @
    }
    

    and I get the P-values on the same lines as the sums of squares, yet the width is still 50 for subsequent chunks.

    0 讨论(0)
提交回复
热议问题