2012-04-28 40 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這可能更適合在這種情況下。