2012-04-28 38 views
7

也许我错过了很明显的,但我一直在努力找到以下示例:我想用R包将一个分析报告写入html文件,使用knitr包。我找到了stitch()函数,但是如果能够更好地控制哪些结果写入html而哪些结果不是这样,那将会很不错。原则上我希望能够代码如下:使用knitr从R内写入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) 
+0

感谢您的提示。但是这个例子不显示你如何在一个HTML文件中嵌入R代码。我宁愿创建一个html文件,然后在WITHIN里写入内容。就像stitch()一样,只是我希望具有更多的灵活性,而不是将所有内容写入html文件。 – 2012-04-28 12:00:02

回答

7

我想我不明白你缺乏什么,但这里是一个很小的例子,我熟了起来。运行这个

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> 
6

编写HTML中,R是在我眼中比写作模板,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这可能更适合在这种情况下。