48188

Iteratively producing latex tables in knitr

Question:

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}

<a href="https://i.stack.imgur.com/CEo9G.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/CEo9G.png" data-original="https://i.stack.imgur.com/CEo9G.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

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. <a href="https://stackoverflow.com/questions/33701038/print-a-list-of-dynamically-sized-plots-in-knitr" rel="nofollow">Print a list of dynamically-sized plots in knitr</a>

Answer1:

The provided code does not match the output you presented. Actually, it produces no output whatsoever.

Step 0: Reproduce output from the question

<ul><li>include=FALSE on the only chunk in the document is quite fatal … replace by echo=FALSE.</li> <li>The main chunk (setup) as well as the template chunk need results="asis". </li> <li>message=FALSE should be a chunk option of setup. Setting it as default options within setup won't affect messages from the current chunk.</li> </ul>

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}

Recommend

  • Escaping LaTeX control symbols in Hmisc::latex
  • In the “Tables”-package: How to get column percentages of a subset of a variable?
  • How to plot stacked proportional graph?
  • Multiple plots on one page using ggplot
  • boxplot won't display with ggvis
  • Iterate twice through a DataReader
  • HttpClient: disabling chunked encoding
  • Clear fused location provider's location for testing
  • android.support.v7.widget.Toolbar VectorDrawableCompat IllegalStateException when using support lib
  • How solve “Qt: Untested Windows version 10.0 detected!”
  • C: Incompatible pointer type initializing
  • How to have background script and something similar to a default popup?
  • d3 v4 drag and drop with TypeScript
  • NHibernate Validation Localization with S#arp Architecture
  • How can I send an e-mail from a vbs script
  • jQuery show() function is not executed in Safari if submit handler returns true
  • RectangularRangeIndicator format like triangular using dojo
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • Accessing IRQ description array within a module and displaying action names
  • Possible to stop flickering java tooltip in heavyweight mode?
  • Does CUDA 5 support STL or THRUST inside the device code?
  • How to model a transition system with SPIN
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • Why winpcap requires both .lib and .dll to run?
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Buffer size for converting unsigned long to string
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Getting Messege Twice Using IMvxMessenger
  • Cant find why the layout is getting smaller
  • How to stop GridView from loading again when I press back button?
  • How to get Windows thread pool to call class member function?
  • Linking SubReports Without LinkChild/LinkMaster
  • Bitwise OR returns boolean when one of operands is nil
  • sending mail using smtp is too slow
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • reshape alternating columns in less time and using less memory
  • costura.fody for a dll that references another dll
  • Binding checkboxes to object values in AngularJs