How to rotate or adjust a big table in Rmarkdown? - r-markdown

Here is my example:
---
title: "There is a reproductible example"
output: pdf_document
---
```{r table-simple, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
require(pander)
panderOptions('table.split.table', Inf)
set.caption("My great data")
my.data <- " # replace the text below with your table data
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement
Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement|Anticonstitutionnellement "
df <- read.delim(textConnection(my.data),header=FALSE,sep="|",strip.white=TRUE,stringsAsFactors=FALSE)
names(df) <- unname(as.list(df[1,])) # put headers on
df <- df[-1,] # remove first row
row.names(df)<-NULL
pander(df, style = 'rmarkdown')
```
In the final PDF outputs, Words overlap.
I use "kable", "table", "print"
Do you have an idea that the words do not overlap?
If the table is very huge, I want that the table rotate automatically in landscape format. Is it possible?

You could try to add the option:
classoption: landscape
in your head section
---
title: "There is a reproductible example"
output: pdf_document
classoption: landscape
---
This will produce a landscape version of the document.

Related

How do I knit child documents with parameters into a main RMarkdown document?

I have a parameterized RMarkdown file, parameterized.Rmd, with the following contents.
---
title: "Parameterized report"
output: html_document
params:
input_df: NULL
---
```{r sec1}
head(params$input_df[, 1:2])
```
I can knit it from the console using rmarkdown::render, generating distinct documents for distinct dataframe inputs. This works as expected.
rmarkdown::render("parameterized.Rmd",
params = list(input_df = mtcars),
output_file = "cars.html")
rmarkdown::render("parameterized.Rmd",
params = list(input_df = iris),
output_file = "iris.html")
I would like to have each of these results be child documents to a common document. My first attempt is with knitr::knit_child, but it does not take params as an argument. So this failed.
---
title: "Main report"
output: html_document
---
```{r test-cars}
knitr::knit_child("parameterized.Rmd", envir = environment(), quiet = T,
params = list(input_df = mtcars))
```
How may I knit together child documents which require parameters?
What worked for me (derived from the documentation once I properly understood it.):
Instead of using the params field in the YAML header, set the values of the parameters inside the main document and call cat on the output of knitr::knit_child. The below files achieved the desired result.
parameterized.Rmd
---
title: "Parameterized report"
output: html_document
---
```{r}
head(df[, 1:2])
```
main.Rmd
---
title: "Main report"
output: html_document
---
# mtcars
```{r mtcars, echo=FALSE, results='asis'}
df <- mtcars
cat(
knitr::knit_child('parameterized.Rmd', envir = environment(), quiet = TRUE)
)
```
# iris
```{r iris, echo=FALSE, results='asis'}
df <- iris
cat(
knitr::knit_child('parameterized.Rmd', envir = environment(), quiet = TRUE)
)
```
Knitting main.Rmd applied the parameterized report to each dataframe.

Flextable table links not linking to my tables

I have generated tables in docx using Rmarkdown (Output: word_document), with captions and links to the tables. For some reason clicking on the links takes me to the top of my word file and not to the relevant table.
Here is some example code: #first time having an rmarkdown related issue, please bare with me
library(officer)
library(flextable)
library(knitr)
library(magrittr)
# set chunks defaults
knitr::opts_chunk$set(echo=FALSE, message=FALSE, warning=FALSE)
#create example df
df1 <- data.frame(col1=c("a","b","c"),
col2=c("1","2","3"))
df2 <- data.frame(col1=c("d","e","f"),
col2=c("4","5","6"))
(Link to table 2) <--- this link should take me to flextable 2, but it doesn't.
#create flextable 1
ft1 <- flextable(df1)
ft1 <- set_caption(ft1, "Caption 1.",
style = "Table Caption",
autonum = run_autonum(seq_id = "tab",bkm="tab1"))
ft1
(Link to Table 1) <---- This link should take me to table 1, but it doesn't.
I set these links in this order to hopefully make the problem clearer.
#links created using format [(Link)](#tab:tab2)
#second flextable
ft2 <- flextable(df2)
ft2 <- set_caption(ft2, "Caption 2.",
style = "Table Caption",
autonum = run_autonum(seq_id = "tab",bkm="tab2"))
ft2
if this is possible using flextable, I am probably making a small mistake somewhere, but can't spot it. So far this is the only function I found that renders docx table output using Rmarkdown
Please help.
I made this example for you:
---
title: "Untitled"
author: "Your Name"
date: "December 16, 2021"
output:
bookdown::word_document2: default
---
```{r setup}
library(flextable)
#create example df
df1 <- data.frame(col1=c("a","b","c"),
col2=c("1","2","3"))
df2 <- data.frame(col1=c("d","e","f"),
col2=c("4","5","6"))
```
```{r Table1}
ft1 <- flextable(df1)
set_caption(ft1, "I love R language")
```
\newpage
```{r Table2}
ft2 <- flextable(df2)
set_caption(ft2, "I hope, it loves me too")
```
\newpage
[(Click, here is the first table)](#tab:Table1)
[(Here is the second)](#tab:Table2)
Good luck and the big success in the process of R learning to you;)
An addition:
```{r Table3, tab.cap = "An another table"}
flextable(df2)
```
\newpage
Ok, here is a third table [(Here is the third)](#tab:Table3).
For anyone else that might run into this problem.
Using the example #manro made above, I got it to work by editing the YAML.
title: "Untitled"
author: "Your Name"
date: "December 16, 2021"
output:
officedown::rdocx_document:
reference_docx: template.docx
library(flextable)
library(officedown)
library(officer)
#create example df
df1 <- data.frame(col1=c("a","b","c"),
col2=c("1","2","3"))
df2 <- data.frame(col1=c("d","e","f"),
col2=c("4","5","6"))
ft1 <- flextable(df1)
set_caption(ft1, "I love R language")
\newpage
ft2 <- flextable(df2)
set_caption(ft2, "I hope, it loves me too")
\newpage
And by removing "tab:" from [(Link)](#tab:tab2) from the link examples below.
[(Click, here is the first table)](#tab:Table1)
[(Here is the second)](#tab:Table2)
leaving me with.
[(Click, here is the first table)](#Table1)
[(Here is the second)](#Table2)

Greek letters RMarkdown PDF plots

I'm trying to generate Greek letters in the axis labels or titles of plots in an RMarkdown file that is generating a PDF. When I run the code the editor or in the console, I see the letter fine, but when the PDF is generated, they disappear. In the short example below, I can see that the subscript operation is working but the Greek letter theta isn't present.
I've tried changing the Typeset LaTeX in PDF using: option - I have pdfLaTeX and XeLaTex - but I see no difference.
---
title: "Untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
plot(1:100, 1:100, xlab = expression(theta[5]))
plot(1:100, 1:100, xlab = expression('theta'[5]))
```
I was using Latin modern font and came across the same problem. The following code fixed it for me. Make sure the math library for the font you are using is called for.
---
title: "Untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, fig.showtext=TRUE}
library("showtext")
font_add("LM Roman 10", regular = "/usr/share/texmf/fonts/opentype/public/lm/lmroman10-regular.otf")
font_add("LM Roman 10", regular = "/usr/share/texmf/fonts/opentype/public/lm-math/latinmodern-math.otf")
plot(1:100, 1:100, xlab = expression(theta[5]))
```

Adding a letter to all table numbers in RMarkdown

I'm using RMarkdown to create Supplementary documents for a paper. These supplements contain many tables. Let's call these documents Supplement A and Supplement B. I want the table numbering to reflect the supplement letter, that is, Table A1 or Table 1A for the first table in Supplement A and so on for all tables.
How can I modify the table numbering to add a letter into the table numbering schema?
Here's an example that will produce a table with normal numbering:
---
title: "Supplement A"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
```
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="MTCars") %>%
kable_styling(latex_options="hold_position", position="left")
```
An inelegant solution using the captioner package (details provided here: https://datascienceplus.com/r-markdown-how-to-number-and-reference-tables/) can create captions and insert them manually just before the code chunk. Combining this with the Latex package caption makes it possible to remove the automatic table naming and numbering if the caption is generated within the code chunk (How to suppress automatic table name and number in an .Rmd file using xtable or knitr::kable?). I've done this in the YAML with \captionsetup[table]{labelformat=empty}, but it can be done in the document body also. Either way, the caption can then be generated within the code chunk, which was important in my case.
This solution stops bookdown referencing from working (because labelformat cannot be empty), but a workaround for table referencing was provided in the link for using the captioner package (and is included below).
---
title: "Supplement A"
header-includes:
- \usepackage{caption}
\captionsetup[table]{labelformat=empty}
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(captioner)
library(stringr)
```
```{r captions}
# Create the caption(s)
caption <- captioner("Table A", FALSE)
tab_1_cap <- caption("Tab_1", "MTCars")
# Create a function for referring to the tables in text
ref <- function(x) str_extract(x, "[^:]*")
```
The following table is `r ref(tab_1_cap)`.
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption=tab_1_cap) %>%
kable_styling(latex_options="hold_position", position="left")
```
An alternative solution is avaiable via LaTeX. Add the following somewhere in the body of the document to change the default figure and table names to include the letter.
\def\figurename{Figure A}
\def\tablename{Table A}
To reference a table or figure in text use, e.g., Table A\#ref(tab:label), after defining the table label as normal.
This alone will leave a space in the table/figure caption (e.g., 'Table A 1' instead of 'Table A1'). This can be solved by adding the following to the YAML:
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
The \DeclareCaptionLabelFormat creates a function (here labeled nospace), which overrides the default caption label when called. #1 represents the label assigned to refer to tables or figures (e.g., 'Table A') and #2 represents the number of the table or figure. The captionsetup lines change the label format for all tables and figures to the format defined by 'nospace'.
Thus, the code produces, e.g., 'Table A1: Table name' as the caption. If instead you wanted, e.g., 'Table A-1: Table name', the code in \DeclareCaptionLabelFormat should be changed to {#1-#2}.
---
title: "Supplement A"
output: bookdown::pdf_document2
toc: false
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(bookdown)
```
\def\figurename{Figure A}
\def\tablename{Table A}
See Table A\#ref(tab:cars) for something about cars.
(ref:cars) Table caption
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="(ref:cars)") %>%
kable_styling(latex_options="hold_position", position="left")
```
Answer inspired by: Figure name in caption using RMarkdown
Caption latex package documentation: https://ctan.org/pkg/caption

Auto-Numbering of Figure and Table Captions for HTML Output in R Markdown

Is there a way to automatically number the figures in captions when I knit R Markdown document into an HTML format?
What I would like is for my output to be the following:
Figure 1: Here is my caption for this amazing graph.
However, I am currently getting the following:
Here is my caption for this amazing graph.
Here is my MWE:
---
title: "My title"
author: "Me"
output:
html_document:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r table1, fig.cap="Here is my caption for an amazing table."}
head(mtcars, 2)
```
I have read that this issue is resolved with Bookdown but I've read the Definitive Guide to Bookdown, cover to cover, and can't find it.
If you wish to have numbered figures, you will need to use an output format provided by bookdown. These include html_document2, pdf_document2 etc. See here for a more comprehensive list of options.
Changing your document example html_document to bookdown::html_document2 will resolve your problem.
---
title: "My title"
author: "Me"
output:
bookdown::html_document2:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r plot2, fig.cap="Here is my caption for another amazing graph."}
plot(y,x)
```
If you want to label tables created by knitr::kable, you will need to specify the caption within the table call itself
```{r table1}
knitr::kable(mtcars[1:5, 1:5], caption = "Here is an amazing table")
```