How to set Multicolumn width (longtable latex) on Rmarkdown - r

I am having some issues with a table built on Rmarkdown to PDF output.
I am using gtsummary to summarise stratified data, then using to_kable_extra in order for export to PDF.
My code looks like this
title: "Untitled"
output:
pdf_document:
keep_tex: yes
date: "2022-08-17"
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(gtsummary)
library(kableExtra)
library(dplyr)
```
```{r}
data <- data.frame(id = rep(1:3), Age = c(20,20,25),Area = letters[1:3])
data %>%select(-id) %>%tbl_strata(strata = Area, .tbl_fun = ~.x %>% tbl_summary(missing = 'no'))%>%
as_kable_extra(
booktabs = TRUE,
longtable = TRUE,
linesep = ""
) %>%
kableExtra::kable_styling(
position = "left",
latex_options = c("striped", "repeat_header"),
stripe_color = "gray!15"
)%>% column_spec(column = 1:4, width = '4cm')
```
The problem comes on the Latex output, with "column_spec" on R i can set latex columns width without issue.
However the multicolumns created for the stratified data I can not from R set their width, and that is my question. How can I achieve this without having to edit the .tex file by myself everytime I want to get this report done.
This is a piece of the Latex file, instead of what is actually happening : \multicolumn{1}{c}{\textbf{a}}; I need it to be \multicolumn{1}{p{4cm}}{\textbf{a}}
\begin{longtable}[l]{>{\raggedright\arraybackslash}p{4cm}>
{\centering\arraybackslash}p{4cm}>{\centering\arraybackslash}p{4cm}>
{\centering\arraybackslash}p{4cm}}
\toprule
\multicolumn{1}{c}{ } & \multicolumn{1}{c}{\textbf{a}} & \multicolumn{1}{c}{\textbf{b}}
& \multicolumn{1}{c}{\textbf{c}} \\
Another possible solution for me would be to turn this multicolumns information to a regular row record susceptible to general column width.

Related

R Markdown adding page break before plot [duplicate]

I am using bookdown to create pdf reports, but my tables are all floating down to the bottom of the page, regardless of how much space there is. See this example:
---
title: "test_doc"
author: "Jake Thompson"
date: "6/30/2017"
output:
bookdown::pdf_document2:
toc: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, collapse = TRUE)
library(tidyverse)
```
# Test heading
Let make a data frame and print it in Table \#ref(tab:test-table)
```{r test-table}
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
knitr::kable(caption = "This is a test")
```
The resulting pdf looks like this:
Why does the table go to the bottom of the page? And is there a way to prevent this behavior?
You can solve this problem with kableExtra by
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
knitr::kable(caption = "This is a test") %>%
kableExtra::kable_styling(latex_options = "hold_position")
It basically insert a [!h] to the LaTeX table environment which will prevent the floating behavior and pin the table at current location.
I had to use
kable_styling(latex_options = "HOLD_position")
Note the uppercase HOLD_position, different from hold_position. See also here.
To be able to use that, I also had to add to the top section of the doc (from How to build a latex kable through bookdown::render_book?):
output:
pdf_document:
extra_dependencies: ["float"]

longtable= T messes up with scaled down table in r markdown pdf

I have a table in my r markdown pdf.
kable(df, "latex", longtable = F, booktabs = T) %>%
kable_styling(latex_options = c("hold_position",
"scale_down"),
fixed_thead = T)
this give a nice table centered in the page, but it is too long for the height of the page. so I added
kable(df, "latex", longtable = T, booktabs = T) %>%
kable_styling(latex_options = c("repeat_header"))
as suggested by many posts. My table now is split across several pages but now wider so that it does not fit within the width of the paper.
How can I keep the original width while still using longtable.
I run the same code suggested here enter link description here
but my table exceeds the width of the paper.
It seems like it is not possible to resize the table when using Longtable = T. When you run this code:
```{r}
library(kableExtra)
kable(iris, "latex", longtable = T, booktabs = T) %>%
kable_styling(latex_options = c("repeat_header", "scale_down"))
```
You get the following warning when trying: Warning in styling_latex_scale_down(out, table_info): Longtable cannot be resized.
Output:
When you add the command full_width = T to the kable_styling, it looks more scaled than before. Check this output:
You could try using kable_styling( full_width = TRUE) which fits a wide (10 column version of iris data across one page). You may need to tweek the column headings so they are legible. Without seeing your actual data it's difficult to suggest anything else.
Update: 2022-06-05 since R version 4.1.3 (2022-03-10) and RStudio 2022.02.3+492 this solution produces an error:
! Dimension too large.
\LT#max#sel #1#2->{\ifdim #2=\wd \tw#
#1\else \number \c#LT#chunks \fi }{\th...
l.328 \end{longtabu}
---
output:
pdf_document
---
```{r}
library(kableExtra)
cbind(iris, iris) |>
kbl("latex", longtable = T, booktabs = T) %>%
kable_styling(latex_options = c("repeat_header"), full_width = TRUE)
```
As Peter said, kable(..., longtable = TRUE) and kable_styling(..., full_witdh = TRUE) no longer work with R version >= 4.1.3 (2022-03-10) and RStudio 2022.02.3+492.
After (many) hours of trial and error with kable and kableExtra, the only solution I found uses pander. It doesn't explicitly control the width of the table, but the result looks good with Peter's example.
---
output:
pdf_document
---
```{r}
library(pander)
cbind(iris, iris) |>
pander("This is a Table")

changing text colour in kable, in Rmarkdown, in latex with % label leads to unwanted "\" proceeding % label when knit

I'm trying to knit a table in a large Rmarkdown document. The table represent disease levels on a farm and thus some are expressed as percentages percentages. When the disease levels are above target I would like to highlight by changing the color of the font to red. This works fine when text does not have a % label, but when I escape the % label the % label in the PDF document is always proceeded by an unwanted "". I'm a vet not a data scientist I have spent many hours on this but can't find an answer.
The original document is extremely complex pulling data from many sources to generate the current disease levels and targets using shiny input to determine various options so not possible to use code from the original document. But I have produced a very minimal reproducible example below
require(kableExtra)
require(scales)
library(knitr)
require(tidyverse)
knitr::opts_chunk$set(echo = TRUE)
MDF = data.frame(a = label_percent()(.07),b = label_percent()(.05))
MDF$a = as.character(MDF$a)
MDF$b = as.character(MDF$b)
MDF[1,] = apply(MDF[1,],2,function(f) gsub("%", "\\\\%", f))
MDF = MDF %>% mutate(a = cell_spec(a, color = ifelse(a > 6,"red","black")))
kable(MDF, "latex", escape = F, booktabs = T)
As far as I get it the issue is that the percent sign in the conditionally formatted cell gets escaped twice, once via the gsub and once via kable itself so that you end up with an additional \textbackslash() inserted in you latex code. Hence, one option to solve your issue would be to manually escape only the percent signs in the column to which you don't apply the conditional formatting:
---
title: "Untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
require(kableExtra)
require(scales)
library(knitr)
require(tidyverse)
MDF = data.frame(a = .07, b = .05) %>%
mutate(across(c(a, b), percent)) %>%
# Escape percent sign in column b only
mutate(across(c(b), ~ gsub("%", "\\\\%", .x))) %>%
mutate(a = cell_spec(a, color = ifelse(a > 6,"red","black")))
kable(MDF, "latex", escape = F, booktabs = T)
```

How to generate automatic numbering of table titles in word using knit in Rmarkdown?

I'm doing a markdown report for my work. I need the outputs in word. Although with KABLE I can place titles on my tables, they are not numbered.
What should I add to kable () or in YAML to get automatic numbering of my tables?
crude example of what I do:
table(cars$speed) %>%
as.data.frame() %>%
kable(caption = "title",digits = 0, format.args = list( decimal.mark = ",",big.mark = "."),booktabs = T) %>%
kable_styling(latex_options = c("hold_position"))
To do this you will need to use the bookdown extensions to markdown. The following is an example rmarkdown (.Rmd) file which does want you want:
---
output:
bookdown::word_document2
---
See Table \#ref(tab:myfirsttable).
```{r myfirsttable, echo = FALSE}
knitr::kable(head(cars, 3), caption = "First three rows of cars dataset")
```
See Table \#ref(tab:mysecondtable).
```{r mysecondtable, echo = FALSE}
knitr::kable(head(iris, 3), caption = "First three rows of iris dataset")
```
Once generated the word document looks like:
For more information see:
https://bookdown.org/yihui/bookdown/a-single-document.html
https://bookdown.org/yihui/bookdown/tables.html

Rendering Table with conditional color in latex as a pdf document with rownames = TRUE (rmarkdown, kable and kableExtra )

I am attempting to output a latex table using r markdown, kable and kableExtra. When i use the option row.names=FALSE instead of row.names=TRUE the latex code generates \vphantom code which produce an error to create the pdf .
It seems the problem is linked to the row_spec option.
Here is Rmarkdown code (.Rmd File):
---
title: "Test"
output:
pdf_document:
fig_caption: true
keep_tex: true
---
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
{r}
library(knitr)
library(kableExtra)
temp <- mtcars[1:5,1:5]
kable(temp, format = "latex", booktabs = F,row.names=F) %>%
kable_styling(position = "center") %>%
row_spec(1, bold = T, background = "red")
The error is :
! Forbidden control sequence found while scanning use of
\check#nocorr#.
\par l.105 ...color{red} \textbf{21.0 &\vphantom{1} 6}
& \textbf{160} & \textbf{...
Do you have any issue of what is happening ?
This is caused by the duplicated rows in the dataframe, as both rows 1 and 2 are the same.
Reviewing the code for row_spec_latex, when kableExtra is used against a kable table, it checks for duplicated rows. If it finds one, it inserts the vphantom argument within the fix_duplicated_rows_latex internal function. This vphantom insertion is then messing up the formatting of the textbf function.
This seems like a slight bug, so it may be worth reporting it as an issue in kableExtra: https://github.com/haozhu233/kableExtra . I am sure that the vphantom is added for a good reason though, but doubt this was an intended consequence.
Supporting code:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
temp <- mtcars[1:5,1:5]
```
```{r}
# Keeping the row names (means all rows are unique)
kable(temp, format = "latex", booktabs = F) %>%
kable_styling(position = "center") %>%
row_spec(1, bold = T, color = "red")
```
```{r}
# Highlighting second row (which doesn't have the vphantom statement)
kable(temp, format = "latex", booktabs = F, row.names=F) %>%
kable_styling(position = "center") %>%
row_spec(2, bold = T, color = "red")
```

Resources