Knitr:只有chunk输出是html(休息保持rmarkdown)

时间:2013-06-13 19:52:46

标签: r knitr r-markdown

我正在尝试制作一个基于knitr的程序,从字符向量读取rmarkdown并写入textConnection。我几乎得到了我想要的东西,但我发现knitr只生成块的html,只是通过rmarkdown传递给html。

以下是代码:

text_input <- "Title
========================================================

This is an R Markdown document. Markdown is a simple formatting syntax for authoring web pages (click the **MD** toolbar button for help on Markdown).

When you click the **Knit HTML** button a web page 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 cache=TRUE}
x <- cars
summary(x)
```

You can also embed plots, for example:

```{r fig.width=7, fig.height=6,cache=TRUE}
plot(x)
```
"
library(knitr)

outfile <- textConnection("foo.html", "w")

pat_md()
render_html()
knit(input=NULL,output=outfile,text=text_input)
close(outfile)
cat(foo.html,sep="\n")

哪个输出:

Title
========================================================

This is an R Markdown document. Markdown is a simple formatting syntax for authoring web pages (click the **MD** toolbar button for help on Markdown).

When you click the **Knit HTML** button a web page 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:

<div class="chunk" id="unnamed-chunk-1"><div class="rcode"><div class="source"><pre class="knitr r">x <- cars
summary(x)
</pre></div><div class="output"><pre class="knitr r">##      speed           dist    
##  Min.   : 4.0   Min.   :  2  
##  1st Qu.:12.0   1st Qu.: 26  
##  Median :15.0   Median : 36  
##  Mean   :15.4   Mean   : 43  
##  3rd Qu.:19.0   3rd Qu.: 56  
##  Max.   :25.0   Max.   :120
</pre></div></div></div>


You can also embed plots, for example:

<div class="chunk" id="unnamed-chunk-2"><div class="rcode"><div class="source"><pre class="knitr r">plot(x)
</pre></div><div class="rimage default"><img src="figure/unnamed-chunk-2.png" title="plot of chunk unnamed-chunk-2" alt="plot of chunk unnamed-chunk-2" class="plot" /></div>
</div></div>

这是预期的行为还是我做错了什么?

1 个答案:

答案 0 :(得分:3)

我用不同的方式解决了这个问题(使用knitr创建md文件,然后使用md - &gt; html创建):

text_input <- "markdown text"
library(knitr)

foo.html <- knit2html(text=text_input)
谢谢一惠。但是正如我在下面的评论中指出的那样,结果html仍然存在一些问题(仅限字符向量输入而不是常规文件)。