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
Related
I want to use bold and italics in a flextable caption. I know that it is possible to apply font syles to text within the header or body of a flextable using the ftExtra package and one can choose different output styles for a caption in word output by officeR. But either these do not work with the caption (ftExtra) or do not provide a style that allows selective application of bold and italics.
Here is some code with the intended markdown in the caption:
library(flextable)
library(dplyr)
iris[1:10,] %>%
flextable() %>%
set_caption(caption = "**Tab. 1:** First ten (*n* = 10) samples of the Iris species dataset")
The caption should read as "Tab. 1: First ten (n = 10) samples of the Iris species dataset"
UPDATE
based on the comment by dario a possible solution would be:
library(flextable)
library(dplyr)
iris[1:10,] %>%
flextable() %>%
add_header_lines("") %>%
compose(
i = 1, part = "header",
value = as_paragraph(
as_chunk("Table 1: ", props = fp_text(bold = TRUE)),
as_chunk("First ten ("),
as_chunk("n", props = fp_text(italic = TRUE)),
as_chunk(" = 10) samples of the Iris species dataset")
)
)
Thank you very much. In the end I need to produce about 20 tables in different chapters and so I will try the suggestion by David to build the captions during knitting a markdown. But it is good to know that there is way, although clunky and not flexible using compose.
I prepared a markdown template for you:
---
title: "Hello World"
header-includes:
- \usepackage{caption}
output:
pdf_document:
latex_engine: xelatex
---
```{r, include = FALSE}
library(flextable)
library(dplyr)
table2 <- flextable(mtcars[1:5, 1:6])
```
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:
\begin{table}[hbtp]
\captionof{table}{Text of the caption.}
`r table2`
\end{table}
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:
An output
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
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
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)
}
I am sorry, I am new to using knitr to make slides. I generally use the latex() function in Hmisc package to generate my tables based on R objects. I would like to produce a slide that shows the r code and then below it displays the properly formatted table. Something like:
``` {r}
latex(tabdat,file="tables/tabdat.tex",ctable=TRUE,caption="A basic table",caption.loc="bottom",label="tab:dat1",row.names=NULL,rowlabel="")
```
So that the finished slide displays the exact r code and the formatted table looking exactly as if I had run latex using \input{tabdat}
I would appreciate any advice on how to accomplish this.
Thanks!
I am a bit puzzled because you talk about PDF/LaTeX output but you are using R markdown tags.
Here are small examples for both cases, R Sweave, i.e. LaTeX output, and R markdown, i.e. HTML output. For creating the LaTeX code there are several packages available (xtable, Hmisc etc.) for HTML AFAIK only xtable.
The main point of how to include the raw output just like it appears in the console is the same for both output types and was already explained by Tyler Rinker above, i.e. by adding results="asis" to the chunk options.
PDF/LaTeX / Rnw-file
\documentclass{article}
\begin{document}
<<echo=FALSE, message=FALSE>>=
library(Hmisc)
library(xtable)
#
<<results='asis'>>=
latex(head(iris), file = '')
#
<<results='asis'>>=
xtable(head(iris))
#
\end{document}
HTML, Rmd-file
```{r echo=FALSE}
library(xtable)
```
```{r results='asis'}
tbl <- xtable(head(iris))
print(tbl, type="html")
```
Look here for more examples and options: http://www.stat.iastate.edu/centers/CCGS/slides/slides-Rtables.pdf