如何在命令行中复制Knit HTML?

Avi*_*ash 17 markdown r rstudio knitr r-markdown

我知道这个问题类似于一个.但我无法在那里得到解决方案,所以再次在这里发布.

我希望通过单击"编织HTML"但通过命令获得与我得到的完全相同的输出.我尝试使用knit2html但它与格式混淆并且不包括标题,kable不起作用等.

例:

这是我的test.Rmd文件,

---
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.
Run Code Online (Sandbox Code Playgroud)

输出:

编织HTML

在此输入图像描述

knit2html

在此输入图像描述

Kon*_*lph 19

文件告诉我们:

如果您不使用RStudio,那么您只需要调用该rmarkdown::render函数,例如:

rmarkdown::render("input.Rmd")
Run Code Online (Sandbox Code Playgroud)

请注意,在使用RStudio中的"Knit"按钮的情况下,基本机制是相同的(RStudio调用rmarkdown::render引擎盖下的功能).

从本质上讲,虽然我没有详尽的所有差异列表,但rmarkdown::render设置的设置要多得多knitr::knit2html.

无论如何,最灵活的渲染输出方式是提供自己的样式表,以根据您的意愿格式化输出.

请注意,您需要手动设置Pandocrmarkdown::render在命令行上使用.


也就是说,这里有两个可以改善knitr::knit2hmtl输出的评论,并且rmarkdown::render在我看来优于使用:

  • 要包含标题,请使用Markdown标题标记,而不是YAML标记:

    # My title
    
    Run Code Online (Sandbox Code Playgroud)
  • 要格式化表,请不要使用原始kable函数.实际上,使用时也是如此rmarkdown::render:表格单元格的对齐完全关闭.Rmarkdown显然使用居中作为默认对齐方式,但此选项几乎从不正确.相反,您应该左对齐文本和(通常)右对齐数字.在撰写本文时,Knitr无法自动执行此操作(据我所知),但为您执行此操作包含过滤器相当容易:

    ```{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)
    })
    ```
    
    Run Code Online (Sandbox Code Playgroud)

  • 为了更好地使用**pander**进行默认列对齐,另请参阅`panderOptions('table.alignment.default')`,例如[here](http://stackoverflow.com/a/27014481/980833). (2认同)