2012-02-14 132 views
14

我在Ubuntu上運行R v2.14.1。我正在編寫一個腳本,它將生成一個數據框,它代表一個結果表。從R數據幀生成LaTeX輸出

我想輸出這個'表'作爲一個.tex文件,以便我可以創建一個'學術刊物'質量表,用於打印。我聽說過Sweave(並且閱讀了關於Sweave的一些概述文檔) - 所以我認爲這是前進的方式。然而,我沒有真正看到Sweave將數據框輸出爲tex文件的例子 - 迄今爲止我所見過的所有Sweave例子都顯得有些做作,並且我不能構建。

是否有一些指導原則可以遵循,從數據框中輸出tex?另外,如果我直接從我的R腳本構建TeX字符串並將字符串保存到文件,它會更簡單(更直接)嗎? (我不清楚,Sweave提供的手動構建TeX字符串的手段)。

+0

還檢查了knitr這是正在積極發展,並具有比更大的靈活性Sweave。 – 2012-02-15 00:43:23

回答

22

xtable包中有一些如何生成表的示例 - 請參閱小插曲。當你寫一個塊的時候,確保你把塊設置爲<<results=tex>>。見Sweave example,例如,this

這是我將如何輸出data.frame。

<<results=tex>> 
    xtable(my.data.frame) 
@ 

和原始結果將看起來是這樣的:

> xtable(my.data.frame) 
% latex table generated in R 2.14.1 by xtable 1.6-0 package 
% Tue Feb 14 10:03:03 2012 
\begin{table}[ht] 
\begin{center} 
\begin{tabular}{rllr} 
    \hline 
& p & q & r \\ 
    \hline 
1 & condition\_a & grp\_1 & 3 \\ 
    2 & condition\_a & grp\_1 & 3 \\ 
    3 & condition\_a & grp\_1 & 4 \\ 
    4 & condition\_a & grp\_1 & 1 \\ 
    5 & condition\_b & grp\_1 & 4 \\ 
    6 & condition\_b & grp\_1 & 3 \\ 
    7 & condition\_b & grp\_1 & 5 \\ 
    8 & condition\_b & grp\_1 & 5 \\ 
    9 & condition\_a & grp\_2 & 4 \\ 
    10 & condition\_a & grp\_2 & 1 \\ 
    11 & condition\_a & grp\_2 & 1 \\ 
    12 & condition\_a & grp\_2 & 1 \\ 
    13 & condition\_b & grp\_2 & 5 \\ 
    14 & condition\_b & grp\_2 & 1 \\ 
    15 & condition\_b & grp\_2 & 5 \\ 
    16 & condition\_b & grp\_2 & 2 \\ 
    \hline 
\end{tabular} 
\end{center} 
\end{table} 
+0

我認爲'='在Sweave代碼中缺失嗎?<> =' – elevendollar 2016-09-29 16:14:10

+0

我試圖在此處應用此提議https://unix.stackexchange.com/q/366637/16920 – 2017-05-30 19:37:58

15

我經常使用來自Hmisclatexdescribe 功能,這讓很多微調。

library(Hmisc) 
d <- data.frame(a=LETTERS[1:5], x=rnorm(5)) 
latex(d, file="")   # If you want all the data 
latex(describe(d), file="") # If you just want a summary 
+0

+1有趣的方法,我一定會在某個階段嘗試。 – 2012-02-14 17:32:10

4

就個人而言,我喜歡R內管理我所有的代碼,而不是一個RNW文件,當我輸出彙總表,而不是寫報告,通過使用cat()sink()這允許您從當前內工作環境,而不是在每次需要重新運行文檔時強制加載和重新加載所有內容。另外,它使R更容易通過大量數據或數據列表來「複製」,「粘貼」或「循環」。應該指出,這有點打破了可重複研究的想法。

這裏是什麼,我將提出一個R檔(記住,當然一個例子\需要轉義\:

dat <- list() 
for(i in 1:15) { 
    dat[[i]] <- sample(c("A","B"),1000,replace=TRUE) # Dummy data 
} 

sink("temp.Rnw") 

cat(" 
\\documentclass{article} 
\\usepackage{Sweave} 
\\begin{document} 
") 

# Print a lot of tables 
invisible(
    lapply(dat, 
     function(x) 
     print(xtable(table(x),caption=names(x)),table.placement="!htp")) 
) 

cat(" 
\\end{document} 
") 

sink() 
Sweave("temp.Rnw") 
compilePdf("temp.Rnw")