【问题标题】:Writing html from within R using knitr使用 knitr 从 R 中编写 html
【发布时间】:2012-05-09 04:26:42
【问题描述】:

也许我错过了显而易见的事情,但我一直在努力寻找以下示例:我想使用 knitr 包将我在 R 中的分析报告写入 html 文件。我找到了stitch() 函数,但是最好能更好地控制哪些结果和绘图写入 html 而哪些不是。原则上,我希望能够编写以下代码:

# some dummy code
library(ggplot)
data <- read.table('/Users/mydata', header=TRUE)
model <- lm(Y~X*Y, data)

# write this result to html:
summary(model)

【问题讨论】:

  • 感谢您的提示。但是这个例子没有显示你如何在 html 文件中嵌入 R 代码。我宁愿创建一个 html 文件并在 R 中写入内容。就像stitch() 一样,只是我希望拥有更多的灵活性,而不是仅仅将所有内容写入 html 文件。

标签: r reporting knitr


【解决方案1】:

我想我不明白你到底缺少什么,但这是我编造的一个最小的例子。运行这个

library(knitr)
knit("r-report.html")

还有例子。

<HTML>
<HEAD>
  <TITLE>Analyzing Diamonds!</TITLE>
</HEAD>

<BODY>
<H1>Diamonds are everywhere!</H1>

<!--begin.rcode echo=FALSE

## Load libraries, but do not show this
library(ggplot2)
library(plyr)
testData <- rnorm(1)
end.rcode-->

This is an analysis of diamonds, load the data.<p>
<!--begin.rcode echo=TRUE, fig.keep="all"
# Load the data
data(diamonds)
# Preview
head(diamonds)
end.rcode-->

Generate a figure, don't show code <p>
<!--begin.rcode echo=FALSE, fig.align="center", dev="png"
# This code is not shown, but figure will output
qplot(diamonds$color, fill=diamonds$color) + 
  opts(title="A plot title")
end.rcode-->

Show some code, don't output the figure<p>
<!--begin.rcode echo=TRUE, fig.keep="none"
# Show the code for this one, but don't write out the figure
ggplot(diamonds, aes(carat, price, colour=cut)) + 
  geom_point(aes(alpha=0.9))
end.rcode-->


And the value testData: <!--rinline testData --> inside a text block.

</BODY>
</HTML>

【讨论】:

    【解决方案2】:

    在我看来,在 R 中编写 HTML 比编写模板和 knit() 它更费力(@dready 给出了一个不错的例子)。代码会相当难看,你会看到很多“猫”跳来跳去。你可能会得到这样的结果:

    sink('test.html') # redirect output to test.html
    cat('<h1>First level header</h1>\n')
    cat('<pre>')
    summary(mtcars)
    cat('</pre>\n')
    sink()
    browseURL('test.html')
    

    无论如何,还有另一个包R2HTML 可能更适合这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      相关资源
      最近更新 更多