|
Sweave in R? Sweave是R中的一個函數(shù),用來生成統(tǒng)計報告的。如果你希望將R的代碼和LaTeX的代碼整合到一個文件中,可以用Sweave函數(shù)生成.tex文件,利用安裝好的LaTeX編譯TeX文件就能生成包含相應(yīng)計算結(jié)果的pdf文件。 Sweave處理的是.Snw文件,其格式幾乎與.TeX文 件相同,不同的是,其中的R代碼包含在<<>>= 和 @ 之間,其中<<>>內(nèi)部可以放置Sweave處理時的參數(shù)。 下面是一個簡單的.Rnw文件的內(nèi)容: \documentclass[a4paper]{article} \title{How to use Sweave? } \author{Jinlong Zhang} \begin{document} \maketitle In this example we use hclust() in R to perform a cluster analysis into a \LaTeX{} document: <<>>= x<-c(1,2,6,8,11) dim(x)<-c(5,1) d<-dist(x) d hc<-hclust(d, "single") dend<-as.dendrogram(hc) @ the dendrograms are also included: \begin{center} <<fig=TRUE,echo=FALSE>>= par(mfrow = c(2, 2),mar = c(4,3,1,2)) plot(dend) plot(dend, nodePar=list(pch = c(1,NA), cex=0.8, lab.cex=0.8), type = "t", center=TRUE) plot(dend, edgePar=list(col = 1:2, lty = 2:3), dLeaf=1, edge.root = TRUE) plot(dend, nodePar=list(pch = 2:1, cex=.4*2:1, col=2:3), horiz=TRUE) @ \end{center} \end{document}
將以上代碼粘貼到記事本中,另存為test.Rnw文件,放置到R的工作目錄,運行Sweave("test.Rnw")即可生成.TeX文件和相應(yīng)的圖形文件。eps圖形文件等將在變異TeX文檔時引用圖形時用到。
可以看到,其中包含了兩塊R代碼: 第一部分為 <<>>= x<-c(1,2,6,8,11) dim(x)<-c(5,1) d<-dist(x) hc<-hclust(d, "single") dend<-as.dendrogram(hc) @ 第二部分為 <<fig=TRUE,echo=FALSE>>= par(mfrow = c(2, 2),mar = c(4,3,1,2)) plot(dend) plot(dend, nodePar=list(pch = c(1,NA), cex=0.8, lab.cex=0.8), type = "t", center=TRUE) plot(dend, edgePar=list(col = 1:2, lty = 2:3), dLeaf=1, edge.root = TRUE) plot(dend, nodePar=list(pch = 2:1, cex=.4*2:1, col=2:3), horiz=TRUE) @
如果想要生成相應(yīng)的pdf,只需用LaTeX變異相應(yīng)的TeX文件即可。
注意:編譯的時候,LaTeX會可能會提示找不到Sweave.sty文件,該文件可在C:\Program Files\R\R-2.9.0\share\texmf目錄下找到,拷貝到TeX文件所在的目錄下即可。
提供幾個進(jìn)一步學(xué)習(xí)的鏈接: Sweave函數(shù)的作者Friedrich Leisch的主頁: http://www.stat./~leisch/Sweave/ www.stat./~charlie/Sweave http://stat./webdav/site/stat/shared/Regression/EPFL-Sweave-powerdot.pdf http://biosun1./courses/individual/bio271/lectures/L7/Sweave-manual-20021007.pdf

|