简体   繁体   中英

Standalone latex table from amended xtable function

I'm trying to create an automated R function which creates a latex file that can be run (without any further amendments to the Latex code) by an external Latex program. I'm aware of KnitR and Sweave but I need something much simpler. Basically for any object that can be printed out through xtable I want to add

%A1 At the top

\documentclass{article}
\pagestyle{empty}
\begin{document}

%A2 at the end

\end{document}

This means that I can just run my analysis and (when I need to) create an external file that can be manipulated by Latex-based programs. I'm not interested in putting all the tables into one document but I want them separate (hence the need for \\begin{document} and \\end{document}. I've been experimenting with add.to.rows (xtable function) but I'm getting nowhere.

Example:

data(tli)
tli.table <- xtable(tli[1:10,])
digits(tli.table)[c(2,6)] <- 0
print(tli.table,floating=FALSE)

How would you add both A1 and A2 so that the result is:

\documentclass{article}
 \pagestyle{empty}
\begin{document}
\begin{table}[ht]
\centering
\begin{tabular}{rrlllr}
  \hline
 & grade & sex & disadvg & ethnicty & tlimth \\ 
  \hline
1 &   6 & M & YES & HISPANIC &  43 \\ 
  2 &   7 & M & NO & BLACK &  88 \\ 
  3 &   5 & F & YES & HISPANIC &  34 \\ 
  4 &   3 & M & YES & HISPANIC &  65 \\ 
  5 &   8 & M & YES & WHITE &  75 \\ 
  6 &   5 & M & NO & BLACK &  74 \\ 
  7 &   8 & F & YES & HISPANIC &  72 \\ 
  8 &   4 & M & YES & BLACK &  79 \\ 
  9 &   6 & M & NO & WHITE &  88 \\ 
  10 &   7 & M & YES & HISPANIC &  87 \\ 
   \hline
\end{tabular}
\end{table}
\end{document}

I got stuck right at the start:

bottom <- list();bottom$pos<- list()
bottom$pos[[1]] <- c(nrow(x))
bottom$command  <-c("\\end{document} \n")
print(xtable(tli[1:10,]),add.to.row=bottom)

I need \\end{document} to be right at the end but if I change

bottom$pos

to

bottom$pos[[1]] <- c(nrow(x)+3)

I get an error. I also haven't included the top part (A1- see above).

Ideally I'd like the code to be as generic as possible so that it can be applied to any xtable output (eg anovas, sideway tables etc...).

Any ideas?

Many thanks

The cat and print.xtable functions both have an 'append' argument:

wrapLatex <- function(dat,fil, ...) {
     cat(c("\\documentclass{article}\n",
           "\\pagestyle{empty}\n",
           "\\begin{document}\n"), file=fil)
   print(dat, file=fil, append=TRUE, ...)
      cat("\\end{document}\n", file=fil, append=TRUE) }
wrapLatex(tli.table, fil="~/test")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM