rstudio / rmarkdown

Dynamic Documents for R
https://rmarkdown.rstudio.com
GNU General Public License v3.0
2.88k stars 975 forks source link

`pander()` and `kable()` causing text to be removed from my pdf output #938

Closed tbradley1013 closed 7 years ago

tbradley1013 commented 7 years ago

Good Morning,

I am working on creating a report in Rmarkdown and have stumbled across a problem that I can't find anyone else having faced before. I am incorporating text, tables, and figures into my document and for some reason on several occasions throughout my pdf output, when there is a table on the page, the text following the table extends past the bottom page margin and then full paragraphs are just missing and the next page with text picks up almost 20 lines of text past where the previous page stops.

I have managed to create an MRE. I realize it is probably longer than most examples, but if it is any shorter than the problem doesn't exist. I have replaced all of my text with randomly generated paragraphs so don't read into any of the text in the document. I have, however, modelled the text after my document down to the number of spaces at the end of every line and th enumber of lines between different blocks. Here is the code for the MRE:

---
title: "Table Issue MWE"
author: "Tyler Bradley"
output:
  pdf_document:
    includes:
      in_header: logo.tex
    toc: no
  html_document:
    toc: yes
    toc_float: yes
  word_document:
    toc: no
documentclass: article
bibliography: bib1.bib
geometry: margin=1in
---

#Section 1  
Fat son how smiling mrs natural expense anxious friends. Boy scale enjoy ask abode fanny being son. As material in learning subjects so improved feelings. Uncommonly compliment imprudence travelling insensible up ye insipidity. To up painted delight winding as brandon. Gay regret eat looked warmth easily far should now. Prospect at me wandered on extended wondered thoughts appetite to. Boisterous interested sir invitation particular saw alteration boy decisively.Supported neglected met she therefore unwilling discovery remainder. Way sentiments two indulgence uncommonly own. Diminution to frequently sentiments he connection continuing indulgence. An my exquisite conveying up defective. Shameless see the tolerably how continued. She enable men twenty elinor points appear. Whose merry ten yet was men seven ought balls. Is branched in my up strictly remember. Songs but chief has ham widow downs. Genius or so up vanity cannot. Large do tried going about water defer by. Silent son man she wished mother. Distrusts allowance do knowledge eagerness assurance additions to. Up unpacked friendly ecstatic so possible humoured do. Ample end might folly quiet one set spoke her. We no am former valley assure. Four need spot ye said we find mile. Are commanded him convinced dashwoods did estimable forfeited. Shy celebrated met sentiments she reasonably but. Proposal its disposed eat advanced marriage sociable. Drawings led greatest add subjects endeavor gay remember. Principles one yet assistance you met impossible. Style too own civil out along. Perfectly offending attempted add arranging age gentleman concluded. Get who uncommonly our expression ten increasing considered occasional travelling. Ever read tell year give may men call its. Piqued son turned fat income played end wicket. To do noisy downs round an happy books.Consulted he eagerness unfeeling deficient existence of. Calling nothing end fertile for venture way boy. Esteem spirit temper too say adieus who direct esteem. It esteems luckily mr or picture placing drawing no. Apartments frequently or motionless on reasonable projecting expression. Way mrs end gave tall walk fact bed.Rooms oh fully taken by worse do. Points afraid but may end law lasted. Was out laughter raptures returned outweigh.  

  1. One
  2. Two
  3. Three
  4. Four
  5. Five

 Agreed joy vanity regret met may ladies oppose who. Mile fail as left as hard eyes. Meet made call in mean four year it to. Prospect so branched wondered sensible of up. For gay consisted resolving pronounce sportsman saw discovery not. Northward or household as conveying we earnestly believing. No in up contrasted discretion inhabiting excellence. Entreaties we collecting unpleasant at everything conviction. Surrounded affronting favourable no mr. Lain knew like half she yet joy. Be than dull as seen very shot. Attachment ye so am travelling estimating projecting is. Off fat address attacks his besides. Suitable settling mr attended no doubtful feelings. Any over for say bore such sold five but hung. It real sent your at. Amounted all shy set why followed declared. Repeated of endeavor mr position kindness offering ignorant so up. Simplicity are melancholy preference considered saw companions. Disposal on outweigh do speedily in on. Him ham although thoughts entirely drawings. Acceptance unreserved old admiration projection nay yet him. Lasted am so before on esteem vanity oh. Cordially convinced did incommode existence put out suffering certainly. Besides another and saw ferrars limited ten say unknown. On at tolerably depending do perceived. Luckily eat joy see own shyness minuter. So before remark at depart.   

Fulfilled direction use continual set him propriety continued. Saw met applauded favourite deficient engrossed concealed and her. Concluded boy perpetual old supposing. Farther related bed and passage comfort civilly. Dashwoods see frankness objection abilities the. As hastened oh produced prospect formerly up am. Placing forming nay looking old married few has. Margaret disposed add screened rendered six say his striking confined. Perhaps far exposed age effects. Now distrusts you her delivered applauded affection out sincerity. As tolerably recommend shameless unfeeling he objection consisted. She although cheerful perceive screened throwing met not eat distance. Viewing hastily or written dearest elderly up weather it as. So direction so sweetness or extremity at daughters. Provided put unpacked now but bringing. Inhabit hearing perhaps on ye do no. It maids decay as there he. Smallest on suitable disposed do although blessing he juvenile in. Society or if excited forbade. 

```{r, echo = F, results = "hide"}
#this chunk includes my required libraries
```

```{r, echo = F, results = "hide"}
#this chunk imports my data
```

```{r, echo = F, results = "hide"}
#This chunk does some tidying
```

```{r timeline, echo = F, fig.width = 14, fig.height=8, fig.align = "center", fig.cap = "Cordially convinced did incommode existence put out suffering certainly. Besides another and saw ferrars limited ten say unknown."}
x <- data.frame(Year = c(1986:2015),
                y = rep(1))
library(ggplot2)
ggplot(x, aes(Year, y))+
  geom_line(lineend = "butt", size = 1.5)+
  theme_bw()
#this chunk creates a timeline - all actual annotation removed for simplicity
```

#2. Section 2
In on announcing if of comparison pianoforte projection. Maids hoped gay yet bed asked blind dried point. On abroad danger likely regret twenty edward do. Too horrible consider followed may differed age. An rest if more five mr of. Age just her rank met down way. Attended required so in cheerful an. Domestic replying she resolved him for did. Rather in lasted no within no. Way nor furnished sir procuring therefore but. Warmth far manner myself active are cannot called. Set her half end girl rich met. Me allowance departure an curiosity ye. In no talking address excited it conduct. Husbands debating replying overcame blessing he it me to domestic.  Do to be agreeable conveying oh assurance. Wicket longer admire do barton vanity itself do in it. Preferred to sportsmen it engrossed listening. Park gate sell they west hard for the. Abode stuff noisy manor blush yet the far. Up colonel so between removed so do. Years use place decay sex worth drift age. Men lasting out end article express fortune demands own charmed. About are are money ask how seven. 

```{r y1, echo = FALSE, fig.width = 12, fig.height=6, fig.align="center", warning=F, fig.cap="Cordially convinced did incommode existence put out suffering certainly. Besides another and saw ferrars limited ten say unknown. On at tolerably depending do perceived. Luckily eat joy see own shyness minuter. So before remark at depart."} 
x <- data.frame(x = c(1:20), y = c(1:20))
ggplot(x, aes(x, y))+
       geom_line()
```

Improve him believe opinion offered met and end cheered forbade. Friendly as stronger speedily by recurred. Son interest wandered sir addition end say. Manners beloved affixed picture men ask. Explain few led parties attacks picture company. On sure fine kept walk am in it. Resolved to in believed desirous unpacked weddings together. Nor off for enjoyed cousins herself. Little our played lively she adieus far sussex. Do theirs others merely at temper it nearer.  

```{r x1, echo =F}
x <- data.frame(x = c("1992A", "1992B", "1997A", "1997B", "1998", "1999", "2002", "2005", "2008",    "2011", "2014"),
           y = c("Jan - June", "July - Dec", "Jan - June", "July - Dec", "June - Sept", "June - Sept", 
                    "June - Sept", "June - Sept", "June - Sept", "June - Sept", "June - Sept"),
           z = c(21.1, 15.0, 13.5, 11.0, 10.4, 9.4, 14.3, 9.9, 6.0, 6.9, 5.0))

colnames(x)[3] <- ""
library(pander)
pander(x, caption = " Men lasting out end article express fortune demands own charmed. About are are money ask how seven.")
```

```{r y2, echo = F, fig.width = 12, fig.height=6, fig.align="center", fig.cap="Cordially convinced did incommode existence put out suffering certainly. Besides another and saw ferrars limited ten say unknown. On at tolerably depending do perceived. Luckily eat joy see own shyness minuter. So before remark at depart."}
df1 <- data.frame(x = rnorm(1:100),
              y = rnorm(1:100))
df2 <- data.frame(x = rnorm(1:100),
              y = rnorm(1:100))
p1 <- ggplot(df1, aes(x, y))+
  geom_point()+
  geom_line()+
  theme_bw()

p2 <- ggplot(df2, aes(x, y))+
  geom_point()+
  geom_line()+
  theme_bw()

library(gridExtra)
grid.arrange(p1, p2, nrow = 1)
```  

#3. Section 3
  Improve him believe opinion offered met and end cheered forbade. Friendly as stronger speedily by recurred. Son interest wandered sir addition end say. Manners beloved affixed picture men ask. Explain few led parties attacks picture company. On sure fine kept walk am in it. Resolved to in believed desirous unpacked weddings together. Nor off for enjoyed cousins herself. Little our played lively she adieus far sussex. Do theirs others merely at temper it nearer. 

```{r, echo = F}
#This chunk changes a character in a data.frame, has no output
```
##3.1 Section 3.1  
  Way nor furnished sir procuring therefore but. Warmth far manner myself active are cannot called. Set her half end girl rich met. Me allowance departure an curiosity ye. In no talking address excited it conduct. Husbands debating replying overcame blessing he it me to domestic.

```{r y3, echo = F, fig.width = 12, fig.height=5, fig.align= "center", fig.cap="Cordially convinced did incommode existence put out suffering certainly. Besides another and saw ferrars limited ten say unknown. On at tolerably depending do perceived."}
df3 <- data.frame(x = rnorm(1:100),
              y = rep(c("first", "second")))
ggplot(df3, aes(x, y))+
  geom_boxplot(fill = "grey80", color = "#3366FF")+
  theme_bw()
 ```

Do to be agreeable conveying oh assurance. Wicket longer admire do barton vanity itself do in it. Preferred to sportsmen it engrossed listening. Park gate sell they west hard for the. Abode stuff noisy manor blush yet the far. Up colonel so between removed so do. Years use place decay sex worth drift age. Men lasting out end article express fortune demands own charmed. About are are money ask how seven. Improve him believe opinion offered met and end cheered forbade. Friendly as stronger speedily by recurred. Son interest wandered sir addition end say. Manners beloved affixed picture men ask. Explain few led parties attacks picture company. On sure fine kept walk am in it. Resolved to in believed desirous unpacked weddings together. Nor off for enjoyed cousins herself. Little our played lively she adieus far sussex. Do theirs others merely at temper it nearer. Meant balls it if up doubt small purse. Required his you put the outlived answered position. An pleasure exertion if believed provided to. All led out world these music while asked. Paid mind even sons does he door no. Attended overcame repeated it is perceive marianne in. In am think on style child of. Servants moreover in sensible he it ye possible. 

Improve him believe opinion offered met and end cheered forbade. Friendly as stronger speedily by recurred. Son interest wandered sir addition end say. Manners beloved affixed picture men ask. Explain few led parties attacks picture company. On sure fine kept walk am in it. Resolved to in believed desirous unpacked weddings together. Nor off for enjoyed cousins herself. Little our played lively she adieus far sussex. Do theirs others merely at temper it nearer. Meant balls it if up doubt small purse. Required his you put the outlived answered position. An pleasure exertion if believed provided to. All led out world these music while asked. Paid mind even sons does he door no. Attended overcame repeated it is perceive marianne in. In am think on style child of. Servants moreover in sensible he it ye possible.  

```{r x2, echo = F}
df <- data.frame(Comparison = "x vs y", 
           pvalue = 0.25)
colnames(df)[2] <- "p-value"
pander(df, caption = "Placing assured be if removed it besides on. Far shed each high read are men over day. Afraid we praise lively he suffer family estate is.")
```

  Improve him believe opinion offered met and end cheered forbade. Friendly as stronger speedily by recurred. Son interest wandered sir addition end say. Manners beloved affixed picture men ask. Explain few led parties attacks picture company. On sure fine kept walk am in it. Resolved to in believed desirous unpacked weddings together. Nor off for enjoyed cousins herself. Little our played lively she adieus far sussex. Do theirs others merely at temper it nearer. Meant balls it if up doubt small purse. Required his you put the outlived answered position. An pleasure exertion if believed provided to. All led out world these music while asked. Paid mind even sons does he door no. Attended overcame repeated it is perceive marianne in. In am think on style child of. Servants moreover in sensible he it ye possible. Forfeited you engrossed but gay sometimes explained. Another as studied it to evident. Merry sense given he be arise. Conduct at an replied removal an amongst. Remaining determine few her two cordially admitting old. Sometimes strangers his ourselves her depending you boy. Eat discretion cultivated possession far comparison projection considered. And few fat interested discovered inquietude insensible unsatiable increasing eat.   

 ```{r x3, echo = F}
x <- data.frame(x = c("1", "2", "3", "4", "5"), 
                   y = c(420, 94, 250, 208, 105))
pander(x, caption = "And few fat interested discovered inquietude insensible unsatiable increasing eat.")

```

Placing assured be if removed it besides on. Far shed each high read are men over day. Afraid we praise lively he suffer family estate is. Ample order up in of in ready. Timed blind had now those ought set often which. Or snug dull he show more true wish. No at many deny away miss evil. On in so indeed spirit an mother. Amounted old strictly but marianne admitted. People former is remove remain as. 

Fulfilled direction use continual set him propriety continued. Saw met applauded favourite deficient engrossed concealed and her. Concluded boy perpetual old supposing. Farther related bed and passage comfort civilly. Dashwoods see frankness objection abilities the. As hastened oh produced prospect formerly up am. Placing forming nay looking old married few has. Margaret disposed add screened rendered six say his striking confined. 

 Perhaps far exposed age effects. Now distrusts you her delivered applauded affection out sincerity. As tolerably recommend shameless unfeeling he objection consisted. She although cheerful perceive screened throwing met not eat distance. Viewing hastily or written dearest elderly up weather it as. So direction so sweetness or extremity at daughters. Provided put unpacked now but bringing. 

Here is what the issue in the output pdf looks like: tableissuemwe

As you can see, the final paragraph on page 3 (which should probably be on the next page to begin with) is cut off and then when the text picks back up on page 5 (page 4 is two floating figures) 16 lines of text have just vanished.

The problem randomly doesn't effect other tables, as I demonstrate in the following image: tableissuemwe2

However, I must say, this seems to be the exception not the rule in my actual report.

I can't figure out what I am doing wrong and I have looked everywhere I can think of for a solution.

My sessionInfo() is as follows:

> sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252       LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] bookdown_0.3       pander_0.6.0       ggthemes_3.3.0     ggsci_2.0          magrittr_1.5       mice_2.25          Rcpp_0.12.8       
 [8] dplyr_0.5.0        WVPlots_0.1        sigr_0.1.0         stringr_1.1.0      reshape2_1.4.2     vtreat_0.5.28      ggtree_1.6.5      
[15] tree_1.0-37        tidyr_0.6.0        ggforce_0.1.1      quantreg_5.29      SparseM_1.74       MASS_7.3-45        ggpmisc_0.2.13    
[22] animation_2.4.1    RColorBrewer_1.1-2 ggmap_2.6.1        maps_3.1.1         gganimate_0.1      ggbiplot_0.55      scales_0.4.1      
[29] plyr_1.8.4         ggrepel_0.6.5      ggfortify_0.3.0.0  gridExtra_2.2.1    mgcv_1.8-16        nlme_3.1-128       ggplot2_2.2.1     
[36] lubridate_1.6.0   

loaded via a namespace (and not attached):
 [1] ape_4.0            lattice_0.20-34    png_0.1-7          rprojroot_1.1      assertthat_0.1     digest_0.6.11      R6_2.2.0          
  [8] backports_1.0.4    MatrixModels_0.4-1 stats4_3.3.2       evaluate_0.10      highr_0.6          RgoogleMaps_1.4.1  lazyeval_0.2.0    
 [15] geosphere_1.5-5    rpart_4.1-10       Matrix_1.2-7.1     rmarkdown_1.3      proto_1.0.0        labeling_0.3       splines_3.3.2     
 [22] udunits2_0.13      munsell_0.4.3      htmltools_0.3.5    nnet_7.3-12        tibble_1.2         jsonlite_1.2       gtable_0.2.0      
 [29] DBI_0.5-1          units_0.4-1        stringi_1.1.2      mapproj_1.2-4      sp_1.2-4           rjson_0.2.15       tools_3.3.2       
 [36] tweenr_0.1.5       jpeg_0.1-8         yaml_2.1.14        parallel_3.3.2     survival_2.39-5    colorspace_1.3-2   knitr_1.15.1 

The logo.tex file in the YAML header has the following code:

\usepackage{titling}

\pretitle{%
  \begin{center}
  \LARGE
  \includegraphics[width=4cm,height=6cm]{logo.png}\\[\bigskipamount]
}
\posttitle{\end{center}}

and the bib1.bib file is: (I have actual sources in mine, but since I don't think that is the problem, I haven't included them)

@misc{source1,
    author     =  "author",
    title        =  "title"
}

I greatly appreciate any help I can get with this as the report is expected in the next week or so!

Thanks, Tyler

tbradley1013 commented 7 years ago

Update Not sure if this warrants closing the issue because other people may still face the same thing, but I was able to fix this problem by using xtable() rather than pander and kable.

yihui commented 7 years ago

I doubt if this MRE is really minimal, e.g. you can probably delete

documentclass: article
bibliography: bib1.bib

in YAML, replace ggplot2 with any base R plots, and so on. Anyway, this issue seems to be the same as I discovered in 2015: https://tex.stackexchange.com/q/276699/9128

If you want to use knitr::kable(), you can set knitr::opts_knit$set(kable.force.latex = TRUE) to force LaTeX output from kable().

github-actions[bot] commented 4 years ago

This old thread has been automatically locked. If you think you have found something related to this, please open a new issue by following the issue guide (https://yihui.org/issue/), and link to this old issue if necessary.