2011-11-03 32 views
4

我在Sweave中面臨兩個格式化挑戰。一個是表格中文本的斜體,第二個是如何將一個列總和行添加到表格的底部。有關詳細信息,請參閱以下MWE。格式Sweave表,兩個挑戰

\documentclass[12pt,letterpaper,oneside]{amsart} 
\usepackage{graphicx} 
\usepackage{longtable} 
\SweaveOpts{keep.source=TRUE}  % Keeps comments in the R code. 
% 
\begin{document} 
% \maketitle 
\section*{The Challenge} 
    Italicize the taxa in the following table and add a row at the bottom which gives the sum of the sites column. 

<<echo=TRUE>>= 
# Creating Data 
taxa <- c("Arabidopsis thaliana", 
    "Populus trichocarpa", 
    "Brachypodium distachyon") 
sites <- c(270,320,240) 
data.df <- data.frame(taxa,sites) 
@ 
~ 
<<label=tab1,echo=TRUE,results=tex>>= 
# Creating Table 
library(xtable) 
data.table <- xtable(data.df, 
    caption="Sweave Output") 
print(data.table, 
    caption.placement="top") 
@ 

    The results should look something like table 2, which was hand coded in \LaTeX. 
\begin{table}[ht] 
    \caption{Manually coded \LaTeX} 
    \begin{tabular}{l l r} 
     \hline 
      & taxa & sites \\ 
     \hline 
     1 & \emph{Arabidopsis thaliana}  & 270 \\ 
     2 & \emph{Populus trichocarpa}  & 320 \\ 
     3 & \emph{Brachypodium distachyon} & 240 \\  
     \hline 
      & Total Sites      & 830 \\ 
     \hline 
    \end{tabular} 
\end{table} 
\end{document} 

回答

4

paste手動添加\emph,並與rbind添加新行,新行的名字爲一個單一的空間。另外,在原始數據框架創建中使用stringsAsFactors=FALSE可以爲分類列添加新值。

然後用sanitize.text.function=identityxtable保留\emph命令中的反斜槓和hline.after以獲得所需的行。

\documentclass[12pt,letterpaper,oneside]{amsart} 
\usepackage{graphicx} 
\usepackage{longtable} 
\SweaveOpts{keep.source=TRUE} % Keeps formatting of the R code. 
\begin{document} 
<<echo=TRUE>>= 
taxa <- c("Arabidopsis thaliana", 
      "Populus trichocarpa",  
      "Brachypodium distachyon") 
sites <- c(270,320,240) 
data.df <- data.frame(taxa,sites, stringsAsFactors=FALSE) 
@ 
~ 
<<label=tab2, echo=TRUE, results=tex>>= 
library(xtable) 
data.df$taxa <- paste("\\emph{",taxa,"}", sep="") 
data.df <- rbind(data.df, ` `=c("Total Sites", sum(data.df$sites))) 
data.table <- xtable(data.df, 
        caption="Sweave Output") 
print(data.table, 
     caption.placement="top", 
     sanitize.text.function=identity, 
     hline.after=c(-1,0,nrow(data.df)-1, nrow(data.df))) 
@ 
\end{document} 
+2

謝謝,亞倫。我已經可以想到這些技術的其他許多應用程序。對'print.xtable'的'sanitize.text.function'參數是我失去了獲取斜體的步驟,'data.frame'的'stringsAsFactors = FALSE'參數是我需要獲得'rbind'的步驟工作。 – Gregory