Rotate a table from R markdown in pdf - r

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)
}

Related

Rmarkdown Not Producing Table Within For In Loop

I'm trying to produce an automated report using Rmarkdown. In this report I have sections with tables. The sections are produced using the following Rmarkdown. However, it refuses to produce any tables(tried using kable and pander) when I hit knit. Knit will just produce the headings, without any tables. When I use the immediate mode, I get the appropriate markdown. So what might I be doing wrong.
```{r, results='asis'}
for(p in names(presentations)) {
deats <- presentations[p][[1]]
cat('#', p, '\n')
pander(deats)
str(deats)
cat('\n')
}
```
If using pander, disable the auto asis results:
```{r, results='asis'}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
for(p in names(mtcars)) {
cat('#', p, '\n')
pander(table(mtcars[, p]))
}
```
For more details, see the related Using pander with knitr vignette
When knitr::kable() or pander::pander() is not top-level R expression, you have to explicitly print it. You may see this post for more background information.

How to refer a figure as a table?

I know, this is probably not the wisest idea anyways, but I need to insert a table as figure/screenshot (.png) but refer to it as a table in the caption. Is it possible?
My gaol is basically the same as here with the only difference that I am working in RStudio with rmarkdown, knitr and bookdown. Ideally, the solution should work for both PDF and HTML output (though, PDF is more important for me now).
As a hack, you could create a dummy table that's printed with a miniscule fontsize, just to get the table caption, and then in the same chunk add the actual table image that you want printed. For example:
---
title: Document Title
output:
bookdown::pdf_document2:
toc: no
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(xtable)
options(xtable.include.rownames=FALSE, xtable.comment=FALSE)
# Dummy table function
dt = function(label, caption=NULL) {
print(xtable(setNames(data.frame(x=numeric()), " "),
caption=caption,
label=paste0("tab:", label)),
hline.after=NULL,
booktabs=FALSE,
size="\\fontsize{0.1pt}{0.1pt}\\selectfont")
}
```
Lorem Ipsum is simply dummy text of the printing and typesetting industry. As you can see, Table \#ref(tab:lab1) shows something. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
```{r, lab1, results="asis", fig.align="center", out.width="6in"}
dt("lab1", "This is table 1")
include_graphics("tab1.png")
```
Now for some more text and then here is Table \#ref(tab:lab2).
```{r, lab2, results="asis", fig.align="center", out.width="4.5in"}
dt("lab2", "This is table 2")
include_graphics("tab2.png")
```
Below, you can see what the output document looks like. As you can see, there some extra space between the caption and the table, due to the small amount of vertical space taken up by the invisible dummy table. Hopefully, some with better knowledge of latex can suggest how to get rid of that space.
I had this same issue and didn't see this question at the time. If you're OK with still having having the horizontal lines at top and bottom, what you can do is make a table that contains nothing but an image of the table you want to display, like this:
```{r echo=F, warning=F}
temp.df <- data.frame(image="![](mytable.png)")
temp.mat <- as.matrix(temp.df)
colnames(temp.mat) <- NULL
knitr::kable(temp.mat, caption="This is my caption")
```
Still a hack but a little less work than the currently accepted answer.

xTable doesn't produce a table in R markdown

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

Width of Pander table in Rmarkdown

I have been trying to use a two-column layout in an Rmarkdown document which include a table rendered using Pander. I would like the table to render to the width of the column but all the options that I have tried do not seem to work. Here is a simple example.
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
<div class = "row">
<div class = "col-md-6">
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars, fig}
plot(pressure)
```
</div>
<div class = "col-md-6">
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
library(pander)
pander(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
</div>
</div>
Not using Pander but learned that kable may be better in this case. I just need to change the chunk option to results='asis' and use kable. I addition formatting of the table can be added easily with the table.attr parameter and use of Bootstrap table classes (http://v4-alpha.getbootstrap.com/content/tables/).
```{r pressure, echo=FALSE, results='asis'}
library(knitr)
#pander(pressure, convert = "html")
kable(pressure, format = "html", table.attr='class="table table-hover"')
```

centering the table generated by kable function of knitr package

I am using the kable() function of knitr package to produce a nice book quality table in a pdf document. The output is as below where the table is placed on the left.
I want to place the table at the center as below.
I would appreciate if anyone can give some advice. I know I can do it using xtable. Is there any way I can do it directly using kable?
The complete reproducible knitr code (.Rnw file) is as below;
\documentclass{article}
\usepackage{booktabs}
\begin{document}
<<results='asis'>>=
library(knitr)
kable(head(women), format='latex', booktabs=TRUE)
#
\end{document}
With kableExtra, you can set the alignment by using:
kable(head(women), "latex", booktabs = T) %>%
kable_styling(position = "center")
http://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

Resources