问题
I'm working on iteratively producing LaTeX tables using knitr. All is well except I'm left with extra markup before each table. Here's a simple example, though this would ideally work as a template for more complex problems, ie different-size tables, varying data sets etc.
What can I do to get rid of the extra text before each table?
\documentclass{article}
\usepackage{setspace, relsize}
\usepackage[margin=.5in, landscape]{geometry}
\usepackage{pdfpages}
\begin{document}
<<setup, include=FALSE>>=
opts_chunk$set(echo=FALSE, warning = FALSE, message = FALSE, cache = FALSE, error = FALSE)
library("ggplot2")
library("knitr")
library("Hmisc")
mytable_function = function(mydata){
foo = as.matrix(head(mydata))
colnames(foo) = names(mydata)
rownames(foo) = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
return(foo)
}
template <- "<<thisthing-{{i}}>>=
mytable = mytable_function(iris[iris$Species == unique(iris$Species)[i],])
latex(mytable, file = '',
title = '',
where = '!h',
caption = 'This is a table',
col.just = rep('r', ncol(mytable)))
@"
for(i in 1:3){
cat(knit(text = knit_expand(text = template, i = i, quiet = TRUE)))
}
@
\end{document}
Fwiw here's a similar question I asked a while ago but because I'm producing tables here and not figures I think this is a slightly different solution. Print a list of dynamically-sized plots in knitr
回答1:
The provided code does not match the output you presented. Actually, it produces no output whatsoever.
Step 0: Reproduce output from the question
include=FALSE
on the only chunk in the document is quite fatal … replace byecho=FALSE
.- The main chunk (
setup
) as well as the template chunk needresults="asis"
. message=FALSE
should be a chunk option ofsetup
. Setting it as default options withinsetup
won't affect messages from the current chunk.
Step 1: Immediate issue
This line
cat(knit(text = knit_expand(text = template, i = i, quiet = TRUE)))
shoud be
cat(knit(text = knit_expand(text = template, i = i), quiet = TRUE))
quiet
is an argument of knit
, not knit_expand
.
Step 2: A better solution
Although this works, it's an overly complicated overkill. The answer you linked to dynamically generated chunks because fig.height
is not vectorized the way it would be required for that case. Here, we can just use a single chunk:
\documentclass{article}
\begin{document}
<<setup, echo = FALSE, results='asis', message = FALSE>>=
mytable_function = function(mydata){
foo = as.matrix(head(mydata))
colnames(foo) = names(mydata)
rownames(foo) = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
return(foo)
}
for(i in 1:3){
mytable = mytable_function(iris[iris$Species == unique(iris$Species)[i],])
Hmisc::latex(mytable,
file = '',
title = '',
where = '!h',
caption = 'This is a table',
col.just = rep('r', ncol(mytable)))
}
@
\end{document}
来源:https://stackoverflow.com/questions/39579712/iteratively-producing-latex-tables-in-knitr