Creating good kable output in RStudio

16,546

opts_chunk$set and opts_current$set don't affect the chunk in which they are called.

from ?opts_chunk

Note the global options set in one chunk will not affect the options in this chunk itself, and that is why we often need to set global options in a separate chunk.

The following option will work:

```{r, results = 'asis'}
kable(er.frame)
```
Share:
16,546
bright-star
Author by

bright-star

Updated on June 04, 2022

Comments

  • bright-star
    bright-star almost 2 years

    I've got a data frame that looks like this:

    er.frame <- structure(c(0.475, 0.525, 0.45, 0.475, 0.45, 0.55, 0.425, 0.5, 
    0.5, 0.4, 0.45, 0.375, 0.55, 0.425, 0.5, 0.475, 0.4, 0.45, 0.375, 
    0.55, 0.425), .Dim = c(7L, 3L), .Dimnames = list(NULL, c("CSP.LDA.error.rate", 
    "CSP.SWLDA.error.rate", "CSP.SVM.error.rate")))
    
    kable(er.frame)
    
    |  CSP.LDA.error.rate|  CSP.SWLDA.error.rate|  CSP.SVM.error.rate|
    |-------------------:|---------------------:|-------------------:|
    |               0.475|                 0.500|               0.500|
    |               0.525|                 0.500|               0.475|
    |               0.450|                 0.400|               0.400|
    |               0.475|                 0.450|               0.450|
    |               0.450|                 0.375|               0.375|
    |               0.550|                 0.550|               0.550|
    |               0.425|                 0.425|               0.425|
    

    I'd like to have that kable output be processed by knitr and make a nice table in the HTML report. Following the documentation in ?kable, I made this snippet:

    ``` {r snippet}
    opts_chunk$set(results='asis')
    kable(er.frame)
    ```
    

    My HTML report, though, as generated by RStudio, is just the echoed console output (or nothing at all, if I add the option output=FALSE):

    ## |  CSP.LDA.error.rate|  CSP.SWLDA.error.rate|  CSP.SVM.error.rate|
    ## |-------------------:|---------------------:|-------------------:|
    ## |               0.425|                 0.400|               0.400|
    ## |               0.425|                 0.475|               0.500|
    ## |               0.400|                 0.400|               0.400|
    ## |               0.425|                 0.425|               0.425|
    ## |               0.425|                 0.325|               0.275|
    ## |               0.350|                 0.375|               0.375|
    ## |               0.450|                 0.425|               0.425|
    

    The above is also what appears in the generated Markdown file with accompanying ``` delimiters, and it looks just fine if I remove the delimiters and the hashes.

    How do I properly output using kable? This question's accepted answer hints at it, but doesn't go as far as the documentation.

    Incidentally, I'm running R 2.15.1, knitr 1.5.15.