How to replicate Knit HTML in a command line?

11,709

The documentation tells us:

If you are not using RStudio then you simply need to call the rmarkdown::render function, for example:

rmarkdown::render("input.Rmd")

Note that in the case using the “Knit” button in RStudio the basic mechanism is the same (RStudio calls the rmarkdown::render function under the hood).

In essence, rmarkdown::render does a lot more setup than knitr::knit2html, although I don’t have an exhaustive list of all differences.

The most flexible way of rendering the output is, at any rate, to supply your own stylesheet to format the output according to your wishes.

Please note that you need to set up Pandoc manually to work with rmarkdown::render on the command line.


That said, here are two remarks that would improve the knitr::knit2hmtl output, and that are superior to using rmarkdown::render in my opinion:

  • To include the title, use a Markdown title tag, not a YAML tag:

    # My title
    
  • To format tables, don’t use the raw kable function. In fact, this is also true when using rmarkdown::render: the alignment of the table cells is completely off. Rmarkdown apparently uses centering as the default alignment but this option is almost never correct. Instead, you should left-align text and (generally) right-align numbers. As of this writing, Knitr cannot do this automatically (as far as I know) but it’s fairly easy to include a filter to do this for you:

    ```{r echo=FALSE}
    library(pander)
    
    # Use this option if you don’t want tables to be split
    panderOptions('table.split.table', Inf)
    
    # Auto-adjust the table column alignment depending on data type.
    alignment = function (...) UseMethod('alignment')
    alignment.default = function (...) 'left'
    alignment.integer = function (...) 'right'
    alignment.numeric = function (...) 'right'
    
    # Enable automatic table reformatting.
    opts_chunk$set(render = function (object, ...) {
        if (is.data.frame(object) ||
            is.matrix(object)) {
            # Replicate pander’s behaviour concerning row names
            rn = rownames(object)
            justify = c(if (is.null(rn) || length(rn) == 0 ||
                            (rn == 1 : nrow(object))) NULL else 'left',
                        sapply(object, alignment))
            pander(object, style = 'rmarkdown', justify = justify)
        }
        else if (isS4(object))
            show(object)
        else
            print(object)
    })
    ```
    
Share:
11,709

Related videos on Youtube

Avinash
Author by

Avinash

I work in the Innovation and Development team in a data analytics company. I am involved for the most part in the labs team of the group that research different algorithms and hence am a heavy R user.

Updated on September 15, 2022

Comments

  • Avinash
    Avinash over 1 year

    I know this question is similar to this one. But I couldn't get a solution there so posting it here again.

    I want to get the exact same output as I get by clicking "Knit HTML" but via a command. I tryied using knit2html but it messes with the formatting and does not include the title, kable does not work etc.

    Example:

    This is my test.Rmd file,

    ---
    title: "test"
    output: html_document
    ---
    
    This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
    
    When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
    
    ```{r}
    library(knitr,quietly=T)
    kable(summary(cars))
    ```
    
    You can also embed plots, for example:
    
    ```{r, echo=FALSE}
    plot(cars)
    ```
    
    Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
    

    Output:

    Knit HTML

    enter image description here

    knit2html

    enter image description here

    • Konrad Rudolph
      Konrad Rudolph over 9 years
      FWIW I prefer the command line output.
    • Avinash
      Avinash over 9 years
      @KonradRudolph: It won't work for me. That's just a sample code I put up. My actual use case has a big table with 8 columns and 10 rows. The commandline output will look ugly.
    • Konrad Rudolph
      Konrad Rudolph over 9 years
      That’s mostly because both options (!) format tables badly by default. See my answer for an improved option.
    • Marek
      Marek over 7 years
  • Avinash
    Avinash over 9 years
    For now, I just use the render function and got it working. But I understand what you mean by it's bad design. I use kable's align option to give my alignment per column. For your solution, I put that as my first code chunk and I should be set right?
  • Konrad Rudolph
    Konrad Rudolph over 9 years
    Yes, exactly. Of course using kable’s align option also works in principle. The reason I’m using pander is that it’s generally quite powerful.
  • Josh O'Brien
    Josh O'Brien over 9 years
    For better default column alignment with pander, see also panderOptions('table.alignment.default'), as e.g. here.