我有一些技巧和变通方法,可以在这里分享xtable和Latex的有趣“功能”。
技巧1:删除列中的重复项和技巧2:使用书签表
首先,加载包并定义我的清理函数
<<label=first, include=FALSE, echo=FALSE>>=
library(xtable)
library(plyr)
cleanf <- function(x){
oldx <- c(FALSE, x[-1]==x[-length(x)])
# is the value equal to the previous?
res <- x
res[oldx] <- NA
return(res)}
现在生成一些假数据
data<-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE),
colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE),
size=rnorm(100,mean=500, sd=150),
age=rlnorm(100, meanlog=3, sdlog=0.5))
#generate a table
datatable<-ddply(data, .(animal, colour), function(df) {
return(data.frame(size=mean(df$size), age=mean(df$age)))
})
现在我们可以生成一个表,并使用clean函数删除label列中的重复条目。
cleandata<-datatable
cleandata$animal<-cleanf(cleandata$animal)
cleandata$colour<-cleanf(cleandata$colour)
@
这是一个普通的xtable
<<label=normal, results=tex, echo=FALSE>>=
print(
xtable(
datatable
),
tabular.environment='longtable',
latex.environments=c("center"),
floating=FALSE,
include.rownames=FALSE
)
@
这是一个普通的xtable,其中自定义函数将重复项转换为NA
<<label=cleandata, results=tex, echo=FALSE>>=
print(
xtable(
cleandata
),
tabular.environment='longtable',
latex.environments=c("center"),
floating=FALSE,
include.rownames=FALSE
)
@
该表使用booktab软件包(并且在标题中需要\ usepackage {booktabs})
\begin{table}[!h]
\centering
\caption{table using booktabs.}
\label{tab:mytable}
<<label=booktabs, echo=F,results=tex>>=
mat <- xtable(cleandata,digits=rep(2,ncol(cleandata)+1))
foo<-0:(length(mat$animal))
bar<-foo[!is.na(mat$animal)]
print(mat,
sanitize.text.function = function(x){x},
floating=FALSE,
include.rownames=FALSE,
hline.after=NULL,
add.to.row=list(pos=list(-1,bar,nrow(mat)),
command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
#could extend this with \cmidrule to have a partial line over
#a sub category column and \addlinespace to add space before a total row
@