문제

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 (e.g. 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")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top