xTable doesn't produce a table in R markdown - r

I am trying to get xtable to insert a table into an R markdown pdf document I'm working on. For some reason, I can't even get the examples from the documentation to reproduce. Instead, the output puts each individual cell on a new line. I've included a screen shot of a portion of my pdf. What am I doing wrong?? Do I need to update a package somewhere? I downloaded xTable today.
```{r, echo=FALSE, results = "asis"}
library(xtable)
data(tli)
print(xtable(tli[1:10,]), type = "html", floating = FALSE, include.rownames = T)
```
Sample of bad pdf

Related

Getting flextable to knit to PDF

I feel like I've gone down a rabbit hole when all I want is some nice tables in my pdf. Long story, here goes:
I want to print some tables to a PDF from r markdown. I usually use Kable and it works fine. That being said, this table is going to have some really long values, and an unknown number of columns that get generated, and I was having a hard time specifying which column would be what width when I didn't know yet in kable. Anyhow, that led me to flextable.
When I knit to html, the table looks great, like so:
But I'm having trouble knitting to pdf. I understand, via other stack answers, that flextable's need to be saved as images to be plotted to pdf. So I have code like this:
ft <- flextable(x)
ft <- autofit(ft)
tf <- tempfile(fileext = ".png")
## Not run:
if( require("webshot2") ){
save_as_image(x = ft, path = "myimage.png")
}
plot(tf)
But at first it gave me the error that I didn't have the webshot2 package, so after some trouble I installed that (it didn't line up with my version of R (I'm on rstudio.cloud) and then when I try to run it now, it says
Am I missing something obvious? How do I save a flextable as an image and then plot it in my pdf?
I've also tried Joanna's solution here: Is it possible to generate the RTable (FlexTable) in pdf with RMarkdown? and r tells me could not find function "as.html". Even though both flextable and htmltools have been loaded.
P.s. providing reproducible data would be very long given all the code that generates the tables and the fact I need it to knit into a pdf, will provide rstudio.cloud link if anyone is interested
You can now produce PDF without the need of webshot package (flextable >= 0.6.0):
---
title: "Untitled"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r}
ft <- flextable(head(airquality))
ft <- autofit(ft)
theme_vader(ft)
```

Placing table next to plot in R Markdown (to pdf / latex)

Is it possible to place a table generated with the xtable (or alternatively the pander) package and a generated plot side-by-side in R markdown knitting to pdf while the rest of the document is not in columns? The following simple example hopefully illustrates the idea:
\begin{multicols}{2}
```{r}
plot(cars)
```
```{r, results='asis'}
library('xtable')
print(xtable(head(cars,5)), type = "latex")
```
\end{multicols}
However, this does not produce the plot. I know that solutions exist using knitr (e.g. here) and for R markdown knitting to HTML (e.g. here) but I don't get them to work for R markdown to pdf.
the gridExtra package works for this without having to go into LaTeX hell. Use the grid.arrange function for side by side charts and what-not.
Works on html and PDF outputs.
Thank you #nycrefugee this already opens some more opportunities. However, there seem to be some problems with xtable outputs. If I use the following code:
library('gridExtra')
library('grid')
library('xtable')
library('lattice')
p = xyplot(1~1)
t = textGrob( print(xtable(head(cars,5)),
type = "latex", label = "test")
)
grid.arrange(p, t, ncol=2)
it produces the following output when compiled to pdf, i.e. the table is shown above the two grobs:
PDF output

Data and plots from different chunks

I am creating a Word report with R studio, markdown and knitr and I am having some troubles.
My r code includes several chunks, becauase between chunks, I want to include the text my report should include.
The problem I have is that: if use a single chunk, then the report is ok, but I can't include text/comments to be written in the report, unless I print also the code (right?). But if I use multiple chunks, then, when compiling, plots are not included in the report and warning messages appear:
pandoc.exe: Could not find image `Scriptv01_files/figure-docx/4.PLOTS-1.png', skipping...
It only works with HTML output: report includes all plots, but not with DOC nor PDF output.
I think the issue is that the data object is created in a different chunk, but I have tried 'cache' and 'autodep' options with no success.
How can this be done? What's the problem with the code?
Many thanks!
Here I provide a code example:
---
output: word_document
---
# PROJECT: IRIS STUDY
#### Statistical Analysis
```{r setup}
require(knitr)
opts_chunk$set(echo = TRUE, message=FALSE, warning=FALSE, comment='')
```
```{r read data}
dataset<-iris
```
### Data Descriptive by Iris Specie
```{r 4. ANALYSE DATA - DATA DESCRIPTION BY SPECIE}
require(ggplot2)
ggplot(dataset, aes(Species)) + geom_bar(aes(fill=Species))+
labs(x = "Species", y = "Number of Flowers")+ ggtitle("Fisher's Iris data set")
```
knitr uses the chunk name as part of the image file name. The chunk name 4. ANALYSE DATA - DATA DESCRIPTION BY SPECIE is invalid and is the reason why the plot is not being created. Replacing the name by a valid name solves the problem:
Avoid spaces and periods . in chunk labels and directory names [Source]

Format text inside R code chunk

I am making some slides inside Rstudio following instructions here:
http://rmarkdown.rstudio.com/beamer_presentation_format.html
How do I define text size, colors, and "flow" following numbers into two columns?
```{r,results='asis', echo=FALSE}
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
```
Output is either HTML (ioslides) or PDF (Beamer)
Update:
Currently the code above will only give something like the following
6683209
1268680
8412827
9688104
6958695
9655315
3255629
8754025
3775265
2810182
I can't do anything to change text size, color or put them into a table. The output of R codechunk is just plain text. Maybe it is possible to put them in a table indeed, as mentioned at this post:
http://tex.aspcode.net/view/635399273629833626273734/dynamically-format-labelscolumns-of-a-latex-table-generated-in-rknitrxtable
But I don't know about text size and color.
Update 2:
The idea weaving native HTML code to R output is very useful. I haven't thought of that. This however only works if I want to output HTML. For PDF output, I have to weave the native Latex code with R output. For example, the code following works using "knitr PDF" output:
```{r,results='asis', echo=FALSE}
cat("\\textcolor{blue}{")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
for (n in rd) {
cat(paste0(n, '\\newline \n')) }
cat("}")
```
You are using results='asis', hence, you can simply use print() and formatting markup. If you want your text to be red, simply do:
```{r,results='asis', echo=FALSE}
print("<div class='red2'>")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
print("</div>")
```
Hope it helps.
It sounds as if you want the output to be either PDF or HTML.
One possibility is the xtable package. It produces tables either in PDF or HTML format. There's no (output-independent) way to specify colour, however. Here's an example.
xt <- xtable(data.frame(a=1:10))
print(xt, type="html")
print(xt) # Latex default
Another option is the pandoc.table function from the pander package. You need the pandoc binary installed. If you have RStudio, you have this already. The function spits out some markdown which then can be converted to HTML or PDF by pandoc.
Here's how you could use this from RStudio. Create an RMarkdown document like this:
---
title: "Untitled"
author: "You"
date: "20 November 2014"
output: html_document
---
```{r, results='asis'}
library(pander)
tmp <- data.frame(a=1:10,b=1:10)
pandoc.table(tmp)
```
When you click "knit HTML", it will spit out a nice HTML document. If you change output to pdf_document, it will spit out a nice PDF. You can edit the options to change output - e.g.
pandoc.table(tmp, emphasize.strong.rows=c(2,4,6,8,10))
and this will work both in PDF or HTML. (Still no options to change colour though. Homework task: fix pandoc.table to allow arbitrary colours.)
Under the hood, knitr is writing markdown, and pandoc is converting the markdown to whatever you like.

Rotate a table from R markdown in pdf

I'm writing in R Markdown and have a contingency table that is quite wide. I am converting the R markdown document to a PDF using pandoc.
Is it possible to rotate or shrink the table? Ideally this would be done without having to switch to LaTeX formatting.
My Attempts:
I've been abusing the figure options in knitr to attempt this, but whether I use kable or xtable, I haven't had any luck. Some permutations I have tried include:
```{r out.extra='angle=90', results='asis'}
library(knitr)
kable(iris[1:5,])
```
``{r size='footnotesize', results='asis'}
library(knitr)
kable(iris[1:5,])
```
```{r out.extra='angle=90', results='asis'}
library(xtable)
xtable(iris[1:5,])
```
```{r size='footnotesize', results='asis'}
library(xtable)
xtable(iris[1:5,])
```
All of these show the table nicely, but do not rotate it.
The code I'm using to knit is:
Rscript -e "library(knitr); knit('table.Rmd', 'table.md')"
And to convert to pdf:
pandoc table.md -o table.pdf
The out.extra='angle=90' only works on Figures, and unfortunately not tables. Here are several potential approaches:
KableExtra (Rotate Page)
You can easily rotate tables using the useful addon package kableExtra. Specifically, the landscape() function will put the table on an single landscape page. It’s useful for wide tables that can’t
be printed on a portrait page.
library(kableExtra)
kable(iris[1:5,],
format = "latex", booktabs = TRUE) %>%
kableExtra::landscape()
The limitation of these function is that it does force a new page, so depending on the size of your table it could leave a bit of blank space.
KableExtra (Scale Width)
You can scale the width of the table using the function kable_styling(latex_options = "scale_down"). This will force the table to the width of the page.
kable(iris[1:5,],
format = "latex", booktabs = TRUE) %>%
kable_styling(latex_options = "scale_down")
For more examples of the kableExtra package, check out the package here: https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf
Stargazer (Rotate Table)
Other options are available, but these largely require the installation of additional LaTeX packages. For example, the stargazer package can print tables in landscape using the float.env argument:
```{r, results="asis"}
stargazer(iris[1:5,],
float.env = "sidewaystable")
```
This requires \usepackage{dcolumn} in LaTeX preamble
Read more about customising your LaTex preamble here: https://tex.stackexchange.com/questions/171711/how-to-include-latex-package-in-r-markdown
You can add some LATEX code in your Rmd file :
\usepackage{lscape}
\usepackage{pdfpages}
Some text on a portrait page.
\newpage
\blandscape
## Title, lorem ipsum
```{r, results = "asis"}
kable(iris[1:5,], caption = "Lorem again")
```
Lorem ipsum...
\elandscape
Some other text on a portrait page.
Can you just use t()?
library(xtable)
xtable(t(iris[1:5,]))
If your table is still to long, split it up into multiple tables. e.g.:
splits = floor(seq(1, ncol(iris), length=5))
for(i in 2:length(splits)){
mini.tab = iris[ , splits[i-1]:splits[i]]
xtable(mini.tab)
}

Resources