跳轉到內容

R 程式設計/出版質量輸出

來自華夏公益教科書

格式化數字

[編輯 | 編輯原始碼]

您可以使用 format() 函式來控制顯示物件的位數和其他特徵。

> df <- data.frame(x = rnorm(10), y = rnorm(10))
> print(df)
            x          y
1  -0.4350953 -0.6426477
2  -0.5947293 -0.2389625
3  -0.7061850 -2.4382016
4  -0.3384038 -0.6322842
5   0.2713353  0.5396409
6  -1.1144711 -2.0321274
7  -1.0356184  1.7217443
8  -2.6665278 -0.3621377
9   0.2975570  0.1598905
10  1.4631458 -0.7995652
> print(format(df, digits=3, scientific=T))
           x         y
1  -4.35e-01 -6.43e-01
2  -5.95e-01 -2.39e-01
3  -7.06e-01 -2.44e+00
4  -3.38e-01 -6.32e-01
5   2.71e-01  5.40e-01
6  -1.11e+00 -2.03e+00
7  -1.04e+00  1.72e+00
8  -2.67e+00 -3.62e-01
9   2.98e-01  1.60e-01
10  1.46e+00 -8.00e-01

Sweave[1] 是一種文學化程式設計語言,它將 LaTeX 和 R 程式碼整合在一起。Sweave 檔案會生成一個 LaTeX 檔案和一個 R 檔案,這兩個檔案可以被編譯。Roger Koenker[2]、Meredith 和 Racine (2009)[3] 以及 Charles Geyer[4] 認為 Sweave 有利於可重複的計量經濟學/統計學研究。

對於文學化程式設計,Sweave 有一些替代方法。其中之一是 Babel,它包含在 Emacs Orgmode[5] 中。該工具允許匯出到 LaTeX 和 HTML。它還允許包含用於各種程式語言(R、Ruby 等)的程式碼塊。

主要思想是編寫一個包含 LaTeX 和 R 程式碼的檔案。LaTeX 程式碼以@開頭,R 程式碼以<<>>=開頭(一些選項可以包含在<<>>).

@
% Some LaTeX code
\section{Results}
I show that ...
<<>>=
# Some R code
qnorm(.975)
@
% Some LaTeX code
$$
\Phi^{-1}(.975) = 1.96 
$$

之間)。該檔案以副檔名.Rnw.rnw. 最後,您使用以下命令從該檔案提取 R 檔案Stangle()以及使用以下命令提取 LaTeX 檔案Sweave(). 以下是一個名為file.Rnw的檔案示例,它生成file.texfile.R

> Sweave("file.Rnw")
Writing to file file.tex
Processing code chunks ...
 1 : echo keep.source term verbatim pdf
 2 : echo keep.source term verbatim pdf
> Stangle("file.Rnw")
Writing to file file.R

然後,您可以對您的 file.tex 執行 LaTeX。這可以使用以下命令完成system()函式或texi2dvi().

# Example under Windows :
system("pdflatex.exe -shell-escape file.tex") # runs pdflatex
system("open file.pdf") # opens the pdf

請注意,您可能需要從網際網路下載 Sweave.sty,因為它不是標準 MikTeX 發行版的一部分。

您還可以使用以下命令在文字中新增結果\Sexpr{}函式。

$
\Phi^{-1}(.975) = \Sexpr{qnorm(.975)} 
$

選項

[edit | edit source]

有一些選項。這些選項可以包含在每個程式碼塊中或在 Sweave 命令中。

  • 對於圖形,您可以使用以下命令將其包含在 tex 檔案中fig=T或使用以下命令將其排除在外fig=F.

預設情況下,圖形以 pdf 和 eps 檔案形式匯出。如果您只需要一種格式,請使用以下命令抑制另一種格式pdf=Feps=F選項。

  • R 程式碼可以使用以下命令顯示在 tex 檔案中echo=T. 如果您不想將其包含在 tex 檔案中,請使用echo=F.
  • R 程式碼可以使用以下命令進行評估eval=T. 如果您不想評估 R 程式碼,請使用eval=F.
  • 結果 
    • results=tex將輸出視為 LaTeX 程式碼
    • results=verbatim將輸出視為 Verbatim(預設值)
    • results=hide不在 LaTeX 輸出中包含結果

這些選項可以傳遞給Sweave()函式。

Sweave("file.Rnw", pdf = T, eps=F, echo = F, results = "verbatim")

它們也可以傳遞給每個程式碼塊。

<<fig=T,pdf=T,eps=F>>=
plot(rnorm(100), col = "red")
@

Sweave 的文字編輯器

[edit | edit source]

Sweave 的主要問題是很少有文字編輯器包含對 Sweave 的語法高亮顯示功能。以下是一些例外 

  • RStudio 是一款非常好的解決方案。它易於安裝和使用,幷包含執行 Sweave 檔案的按鈕。
  • Vim 為 Sweave 檔案提供語法高亮顯示 (R no web syntax)
  • Emacs + ESS (Emacs Speaks Statistics) 為 Sweave 檔案提供完全支援。它包括執行 Sweave 檔案的鍵盤快捷鍵和在 LaTeX 和 R 之間切換的語法高亮顯示。
  • Eclipse StatET 外掛為 Sweave (LaTeX/R) 文件提供支援,其中包含所有基本功能(語法高亮顯示、括號匹配、切換註釋等),並能檢測到 R 程式碼塊。

另請參見

[edit | edit source]

一些 Sweave 文件示例 

  • Charles Geyer foo.Rnw 示例
  • Julien Barnier 的 R 入門(法語文件)
  • 技巧 : 輸入filetype:Rnwfiletype:Snw在 Google 中搜索以獲取 Sweave 檔案
  • 請注意,您可以在 R 庫資料夾中瀏覽以找到大量示例。文件通常使用 Sweave 編寫,並且 Sweave 檔案通常包含在包中。例如,請參閱 **np** 包中的 doc 資料夾。

一些講義 

  • "用 Sweave 和 DOCSTRIP 進行文學程式設計" (pdf) 作者:Michael Lundholm
  • Charles Geyer 2008 "Sweave 演示" (pdf)(簡短)
  • 用 APA 風格學習 Sweave[6]

一些軟體包

  • pgfSweave
  • ascii
  • cacheSweave
  • exam 自動生成試卷

一些替代文學程式設計包 

  • odfWeave 包,用於使用 OpenOffice 進行 Sweave。
  • knitr
  • decumar,由 Hadley Wickham 開發的 R 文學程式設計介面[7]
  • relax
  • wikirobot[8] 與 Sweave 類似,但適用於 MediaWiki。

Pubprint

[edit | edit source]

Pubprint 是一款小型實用程式,能夠將統計檢驗的輸出轉換為可發表的輸出。Pubprint 能夠將輸出匯出為多種格式(HTML、LaTeX、Markdown 和純文字),但不幸的是僅支援 APA 風格(美國心理學會的出版風格)。然而,這種風格被廣泛使用,並且可能在更多情況下適用。

示例

[edit | edit source]
> library("pubprint")
> pprint(t.test(rnorm(30), rnorm(30)))
[1] "(\\ensuremath{M\\ifmmode_{x}\\else\\textsubscript{x}\\fi=-0.05,M\\ifmmode_{y}\\else\\textsubscript{y}\\fi=0.09,t[57.74]=-0.49,p=.628})"

顯然,pubprint 列印的是 LaTeX 格式的字串,但可以更改輸出格式(根據手冊,pubprint 旨在與 knitr 一起使用,如果與 knitr 一起使用,它會自動檢測輸出格式)

> pp_opts_out$set(pp_init_out("plain"))
> pprint(t.test(rnorm(30), rnorm(30)))
[1] "(M_x=-0.14,M_y=-0.24,t[57.4]=0.41,p=.682)"
> pprint(cor.test(rnorm(30), rnorm(30)))
[1] "(r=-.08,p=.693)"

輸出可以貼上到文件中,也可以包含在 knitr/sweave 中\Sexpr{}語句。

匯出到 LaTeX

[edit | edit source]

R 具有許多函式,允許它將結果匯出到 LaTeX[9]

通用函式

[edit | edit source]

toLatex()位於 **utils** 包中。

  • 請注意toLatex()不處理矩陣。
  • toLatex()已在 **memisc** 包中進行修改,以處理矩陣和 ftables。
> toLatex(sessionInfo())
\begin{itemize}
  \item R version 2.2.0, 2005-10-06, \verb|powerpc-apple-darwin7.9.0|
  \item Base packages: base, datasets, grDevices,
    graphics, methods, stats, utils
\end{itemize}
  • mat2tex()(**sfsmisc**)將矩陣匯出到 LaTeX。
  • tex.table()(**cwhmisc**)包將資料框匯出到 LaTeX 表格。
> tex.table(mydat)
\begin{table}[ht]
\begin{center}
\begin{footnotesize}
\begin{tabular}{r|rrr}
\hline
 & y & x1 & x2\\ \hline
1 & -0.09 & -0.37 & -1.04\\ 
2 & 0.31 & 0.19 & -0.09\\ 
3 & 3.78 & 0.58 & 0.62\\ 
4 & 2.09 & 1.40 & -0.95\\ 
5 & -0.18 & -0.73 & -0.54\\ 
6 & 3.16 & 1.30 & 0.58\\ 
7 & 2.78 & 0.34 & 0.77\\ 
8 & 2.59 & 1.04 & 0.46\\ 
9 & -1.96 & 0.92 & -0.89\\ 
10 & 0.91 & 0.72 & -1.1\\ 
\hline
\end{tabular}
\end{footnotesize}
\end{center}
\end{table}


  • xtable()(**xtable**)將各種物件(包括表格、資料框、lm、aov 和 anova)匯出到 LaTeX。
> # lm example
> library(xtable)
> x <- rnorm(100)
> y <- 2*x + rnorm(100)
> lin <- lm(y~x)
> xtable(lin)
% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Sun Sep 23 21:54:04 2012
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrr}
  \hline
 & Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\ 
  \hline
(Intercept) & -0.0407 & 0.0984 & -0.41 & 0.6803 \\ 
  x & 2.0466 & 0.1043 & 19.63 & 0.0000 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}

> # table example
> x <- sample(1:10, 30, replace = T)
> tab <- table(x)
> tab <- cbind(tab, prop.table(tab))
> colnames(tab) <- c("N.", "Prop.")
> xtable(tab, digits = c(0, 0, 2))
% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Sun Sep 23 22:06:36 2012
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrr}
  \hline
 & N. & Prop. \\ 
  \hline
1 & 5 & 0.17 \\ 
  3 & 1 & 0.03 \\ 
  4 & 3 & 0.10 \\ 
  5 & 6 & 0.20 \\ 
  6 & 5 & 0.17 \\ 
  7 & 3 & 0.10 \\ 
  8 & 2 & 0.07 \\ 
  9 & 2 & 0.07 \\ 
  10 & 3 & 0.10 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}

另請參見 

  • 由 Romain François 開發的 **highlight** 包將 R 程式碼匯出到 LaTeX 和 HTML。
  • format.df()latex()位於 **Hmisc** 包中。
  • **MEMISC** 和 **quantreg** 包包含其他latex()函式。

描述性統計

[edit | edit source]
  • estout 包。
  • reporttools 包包含一些用於描述性統計表格的函式[10]

估計結果

[edit | edit source]
  • stargazer 包提供了一種將回歸結果匯出到 LaTeX 的簡便方法[11]
  • texreg 提供了相同的功能[12]
  • estout 包提供了與 Stata 的類似函式esttabestout實用程式[13]。估計值使用以下命令儲存eststo()並使用以下命令列印esttab(). 它們可以匯出到 CSV 和 LaTeX。這些函式支援lm, glmplm物件(請參閱 **plm** 包)。
  • apsrtable()(**apsrtable**)將多個迴歸的結果匯出到 LaTeX,其方式類似於《美國政治科學評論》出版標準。
  • xtable(**xtable** 包)匯出資料框、矩陣、估計結果[14]xtable()也可以用於將結果匯出到 HTML 檔案。
  • 由 Paul Johnson 開發的 outreg() 函式[15]Stataoutreg[16] 函式相似。請參閱 "R you ready ?" 博文,瞭解此主題的資訊。
  • mtable()toLatex()位於 'memisc 包中。
N <- 10^3
u <- rnorm(N)
x1 <- rnorm(N)
x2 <- x1 + rnorm(N)
y <- 1 + x1 + x2 + u
lm1 <- lm(y ~ x1 + x2 )
lm2 <- lm(y ~ x1 + x2 + I(x1*x2))

library(estout)
estclear() # clear all the eststo objects
eststo(lm1) 
eststo(lm2)
esttab() # print it

library("apsrtable")
apsrtable(lm1,lm2)

library(xtable)
xtable(lm1)
tab <- xtable(lm1)
print(tab,type="html")

source("http://pj.freefaculty.org/R/WorkingExamples/outreg-worked.R")
outreg(list(lm1,lm2))

library("memisc")
toLatex(mtable(lm1,lm2))

匯出到 HTML

[edit | edit source]

rpublisher[17] 是一種文學程式語言,它將結果釋出為 HTML 格式(它基於 python,最後更新於 2008 年)。


參見 R2HTMLxtablehwriterprettyRhighlightHTMLUtils


wiki.table()hacks 包中,將矩陣或資料框匯出到 Mediawiki 表格標記(如本維基和其他許多維基中使用的那樣)。

> wiki.table(matrix(1:16,4),caption="Test")
{|  
|+ Test 
| 1 || 5 || 9 || 13 
|-
| 2 || 6 || 10 || 14 
|-
| 3 || 7 || 11 || 15 
|-
| 4 || 8 || 12 || 16 
|}

參考文獻

[編輯 | 編輯原始碼]
上一篇:文字處理 索引
華夏公益教科書