跳至內容

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

[edit | edit source]

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 等)的程式碼塊。

語法

[edit | edit source]

主要思路是編寫一個包含 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儲存。最後,可以使用Stangle()從該檔案中提取一個 R 檔案,並使用Sweave()提取一個 LaTeX 檔案。以下是一個名為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 命令中。

  • 對於圖形,您可以使用fig=T將它們包含在 tex 檔案中,或者使用fig=F.

不包含它們。預設情況下,圖形將匯出為 pdf 和 eps 檔案。如果您只需要一種格式,請使用以下選項來抑制另一種格式pdf=Feps=F選項。

  • 可以使用echo=T將 R 程式碼顯示在 tex 檔案中。如果您不想在 tex 檔案中包含它,請使用echo=F.
  • 可以使用eval=T來評估 R 程式碼。如果您不想評估 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 入門介紹(法語文件)
  • 技巧:在 Google 中輸入filetype:Rnwfiletype:Snw即可找到 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[7] 開發的 R 文學程式設計介面
  • 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 包中。
  • MEMISCquantreg 包包含其他latex()函式在文字中新增結果。

描述性統計

[編輯 | 編輯原始碼]
  • estout 包。
  • reporttools 包包含一些用於描述性統計表的功能[10]

估計結果

[編輯 | 編輯原始碼]
  • stargazer 包提供了一種簡單的方法來將回歸結果匯出到 LaTeX[11]
  • texreg 提供了相同的功能[12]
  • estout 包提供類似於 Stata 的函式esttabestout實用程式[13]。估計使用eststo()儲存,並使用esttab()列印。它們可以匯出到 CSV 和 LaTeX。這些函式支援lm, glmplm物件(參見 plm 包)。
  • apsrtable()(apsrtable) 以類似於美國政治科學評論出版標準的方式將多個迴歸的結果匯出到 LaTeX。
  • Thextable(xtable 包) 匯出資料框、矩陣、估計結果[14]xtable()也可以用來將結果匯出到 HTML 檔案。
  • The outreg() function[15] developped by Paul Johnson is similar to the Stataoutreg[16] function. See "R you ready ?" post on this topic.
  • mtable()toLatex()in the 'memisc package.
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

[編輯 | 編輯原始碼]

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


See R2HTML, xtable, hwriter, prettyR, highlight, HTMLUtils


wiki.table()in the hacks package export a matrix or a dataframe into Mediawiki table markup (as used on this wiki and many others).

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

參考文獻

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