Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R, knitr doesn't respect order of chunks and text

Tags:

r

latex

knitr

Imagine I knit this Rnw file:

\documentclass{article}

\begin{document}

Table1
<<example,results='asis', echo=FALSE>>=
require(xtable)
nn <- 15
mydata <- data.frame(A=1:nn,C=nn:1, C=runif(nn), D=rnorm(nn))
xtable(mydata, caption="Table1")
@

Table2
<<example2,results='asis', echo=FALSE>>=
xtable(mydata, caption="Table2")
@

Table3
<<example3,results='asis', echo=FALSE>>=
xtable(mydata, caption="Table3")
@

\begin{obeylines}
Just some text 
\end{obeylines}


\end{document}

It's a simple example that just prints some text and three tables.

Strangely it doesn't respect the order of what I've written on my code. I get this (sideview of the two pdf pages) enter image description here

But "Table3" text should appear before the table3 itself and after table2, and the text "just some text" should appear at the very end of the document.

If I write several lines there it breaks the lines.

I understand that if a table doesn't fit on a place it must be moved to the next page but so should be done with the following text and tables.

I've also observed that in other examples some tables are reallocated randomly when they don't fit well.

How can I prevent knitr from doing this? I don't know whether is a knitr problem or latex.

I'm using Texlive 2015, Rstudio, R 3.2.3 and Windows 10 and the latest version of all packages involved.

like image 694
skan Avatar asked Apr 02 '16 00:04

skan


1 Answers

By default print.xtable() produces a LaTeX \table{...} environment, which is defined as a floating object. See `?print.xtable and try e.g.

<<example2,results='asis', echo=FALSE>>=
print(xtable(mydata, caption="Table2"),floating=FALSE)
@

(untested ...)

alternatively you could try table.placement="H"; you may need \usepackage{float} (see this question from tex.stackexchange.com).

(also untested ...)

like image 149
Ben Bolker Avatar answered Sep 30 '22 17:09

Ben Bolker