我正在为Sweave中的两个格式挑战而苦苦挣扎。一个是表中文本的斜体,第二个是如何将一个列求和行添加到表的底部。有关详细信息,请参阅以下MWE。
\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}
答案 0 :(得分:4)
使用\emph
手动添加paste
,并使用rbind
添加新行,将新行的名称设置为单个空格。另外,在原始数据框创建中使用stringsAsFactors=FALSE
可以为分类列添加新值。
然后使用sanitize.text.function=identity
让xtable
在\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}