2010-04-28 20 views
6

Je souhaite avoir un document sweave qui inclura un nombre variable de tables. J'ai pensé que l'exemple ci-dessous fonctionnerait, mais ce n'est pas le cas. Je veux faire une boucle sur la liste foo et imprimer chaque élément comme sa propre table.Comment inclure plusieurs tables par programme dans un document Sweave en utilisant R

% 
\documentclass[a4paper]{article} 
\usepackage[OT1]{fontenc} 
\usepackage{longtable} 
\usepackage{geometry} 
\usepackage{Sweave} 
\geometry{left=1.25in, right=1.25in, top=1in, bottom=1in} 
\listfiles 
\begin{document} 

<<label=start, echo=FALSE, include=FALSE>>= 
startt<-proc.time()[3] 
library(RODBC) 
library(psych) 
library(xtable) 
library(plyr) 
library(ggplot2) 
options(width=80) 

#Produce some example data, here I'm creating some dummy dataframes and putting them in a list 
foo<-list() 
foo[[1]]<-data.frame(GRP=c(rep("AA",10), rep("Aa",10), rep("aa",10)), X1=rnorm(30), X2=rnorm(30,5,2)) 
foo[[2]]<-data.frame(GRP=c(rep("BB",10), rep("bB",10), rep("BB",10)), X1=rnorm(30), X2=rnorm(30,5,2)) 
foo[[3]]<-data.frame(GRP=c(rep("CC",12), rep("cc",18)), X1=rnorm(30), X2=rnorm(30,5,2)) 
foo[[4]]<-data.frame(GRP=c(rep("DD",10), rep("Dd",10), rep("dd",10)), X1=rnorm(30), X2=rnorm(30,5,2)) 
@ 

\title{Docuemnt to test putting a variable number of tables into a sweave Document} 
\author{"Paul Hurley"} 
\maketitle 

\section{Text} 

This document was created on \today, with \Sexpr{print(version$version.string)} running 
on a \Sexpr{print(version$platform)} platform. It took approx \input{time} sec to process. 

<<label=test, echo=FALSE, results=tex>>= 
cat("Foo") 
@ 
that was a test, so is this 
<<label=table1test, echo=FALSE, results=tex>>= 
print(xtable(foo[[1]])) 
@ 
\newpage 

\subsection{Tables} 

<<label=Tables, echo=FALSE, results=tex>>= 
for(i in seq(foo)){ 
    cat("\n") 
    cat(paste("Table_",i,sep="")) 
    cat("\n") 
    print(xtable(foo[[i]])) 
    cat("\n") 
    } 
#cat("<<label=endofTables>>= ") 
@ 


<<label=bye, include=FALSE, echo=FALSE>>= 
endt<-proc.time()[3] 
elapsedtime<-as.numeric(endt-startt) 
@ 
<<label=elapsed, include=FALSE, echo=FALSE>>= 
fileConn<-file("time.tex", "wt") 
writeLines(as.character(elapsedtime), fileConn) 
close(fileConn) 
@ 

\end{document} 

Ici, le morceau de table1test fonctionne comme prévu, et produit une table basée sur la trame de données dans foo [[1]], mais la boucle ne produit que le tableau (underscore) 1 ....

+0

+1 Bel exemple reproductible. Si vous regardez le document latex final, voyez-vous les autres tables? – Shane

Répondre

6

Ceci est causé par le trait de soulignement dans cette déclaration:

cat(paste("Table_",i,sep="")) 

Si vous changez à

cat(paste("Table ",i,sep="")) 

Or

cat(paste("Table\\textunderscore",i,sep="")) 

Il s'exécute. Vouliez-vous que ces chiffres soient des indices?

+0

visage <-palm .... Merci Shane, j'ai passé deux heures à regarder ça et je ne l'ai jamais vu .... – PaulHurleyuk