How to print single asterisk in R Markdown table using 'kable'? - r

I created a table in an R Markdown document which I want to print in html format using kable and kable_styling from the kableExtra package. One column contains cells that should only show one single asterisk "*".
In the html, these cells are depicted as points / bulletpoints?! How can I change my output in a way that the single asterisks are just printed as asterisks (like the cells containing "**" or "***")?
Example Code:
```{r example}
df <- data.frame(type = c("a", "b", "c", "d"),
number = runif(4),
asterisks = c("*", "*", "**", "***"))
df %>%
kable(caption = "Single asterisk looks like point...") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = F, position = "left")
```
html output:
Any help is highly appreciated. Thanks!

Related

Missing symbols when combining formattable and kableExtra when creating a data-table in R

I'm attempting to combine the use of R packages formattable and kableExtra to create a data-table. Using formattable, I'm adding a green thumbs up symbol to one particular column ("b") for numbers > 0, this displays correctly. I then pass my table to "kable" so that I can add the "hover" feature, widen column 1, and add grouped headers. However, whilst the produced data-table correctly displays the "hover" feature and correct grouped headers, the green thumbs up feature (derived from formattable) is missing.
Here is a minimal, reproducible example:
library(formattable)
library(kableExtra)
library(dplyr)
labels <- c("A", "B", "C")
a <- c(0.22, 0.28, 0.23)
b <- c(890.53, 346.84, 1119.63)
c <- c(6.56, 5.70, 4.59)
d <- c(0.0048, -0.3194, -0.2720)
e <- c(-0.3212, 0.1280, 0.0755)
f <- c("-", "-", "-")
df <- tibble(labels,a,b,c,d,e,f)
customGreen = "#71CA97"
# function to assign a thumbs up to numbers > 0
custom_thumb <- formatter("span", style = x ~ style(font.weight = "bold",
color = ifelse(x > 0, customGreen, ifelse(x < 0, customRed, "black"))),
x ~ icontext(ifelse(x > 0, "thumbs-up", ""), x)
)
# use formattable to add thumbs up symbols
df_frmt <- formattable(df, align =c("l","c","c","c","c","c","c"),
list(`labels` = formatter("span"),
`b` = custom_thumb))
# pass the resulting table to kable for further edits
df_kbl <- kbl(df_frmt, escape = T) %>%
kable_styling("hover", full_width = F) %>%
column_spec(1, width = "5cm") %>%
add_header_above(c(" "=2, "Group 1" = 2, "Group 2" = 2, " " = 1))
df_kbl
Given that the hover feature and grouped headers is working well, is the issue something to do with escaping html? I've tried both "escape=T" and "escape=F" in the kable edit though there's no change. I know that both of these packages can be used together from reading the "Integration with formattable" section of this website. I don't know if it's relevant or not, but I'm running this code in an RMarkdown file inside RStudio. Any helps is appreciated!
Following your mentioned link, combining formattable and kableExtra is not done by passing a formattable to the kbl function.
Instead you might use custom (your custom_thumb) or original functions (color_bar or color_tile) from formattable and integrate them into the kableExtra syntax.
df %>%
mutate(b = custom_thumb(b)) %>%
kable("html", escape = F, align = c("l","c","c","c","c","c","c")) %>%
kable_styling("hover", full_width = F) %>%
column_spec(1, width = "5cm") %>%
add_header_above(c(" " = 2, "Group 1" = 2, "Group 2" = 2, " " = 1))

R Aligning table content to decimal points in kable

I've created a table in RMarkdwon (PDF) with the knitr and kableExtra packages.
I can choose in the kable-function between left,center or right- alignments.
But I want that the content of the table cells are aligned to the decimal points.
In this case it is difficult since there are asterisks behind the numbers indicating the significance.
Here is a reproduceable example:
library(tidyverse)
library(knitr)
library(kableExtra)
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
kable(format = "latex", booktabs=T, escape = T)%>%
kable_styling(position = "center", latex_options = "hold_position")
Which produces this table:
Can someone give me an easy solution directly in R?
If this should not be possible, how would an edit in the latex code look like?
Many thanks in advance!
Here is the table provided by bttomio:
One solution could be intersing the variable names in {} recommended by https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf page 28.
The code then looks like this:
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
rename_all( ~ str_c("{ ",.," }"))%>%
kable(format = "latex", booktabs=T, escape = T)%>%
kable_styling(position = "center", latex_options = "hold_position")
And the table corresponds to the desired output:
But the problem is the full-width-option in the kable_styling-function. If I set this option to TRUE the linebreak of large column names disappears.
Here is a first try:
---
output: pdf_document
header-includes:
- '\usepackage{siunitx}'
- '\newcolumntype{d}{S[table-format=3.2]}'
---
```{r}
library(tidyverse)
library(knitr)
library(kableExtra)
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
kable(format = "latex", booktabs=T, escape = T, align = "d")%>%
kable_styling(position = "center", latex_options = "hold_position")
```

How to center flushed-right column text in Kable?

I am having a dataframe with both character and numeric columns. I am trying to center the character column (which is done) and (I don't know how to) center flushed-right numeric column. Further, both column names are centered:
Some relevant posts (this and this), but I couldn't incorporate the techniques (if relevant) to my code.
The following code produces the table below:
df <- data.frame(name = c("a", "bb", "ccc"), number = c(10, 193048, 200))
kable(df, format="latex", align = c("c", "r")) %>%
kable_styling(full_width = TRUE) %>%
row_spec(0, align = "c")
I understand that I can use LaTeX code to produce a single user-customised table. But I need the example to be reproducible in Rmd (imagine I have lots of df) and therefore need to specify within kable().
Should I modify the LaTeX table environment (i.e. \begin{tabu} to \linewidth {>{\centering}X>{\centering}X}) and if so how in R, or use something like multirow to customise the second column??
Thanks to #Fran from this post, answer below:
df <- data.frame(name = c("a", "bb", "ccc"), number = c(10, 193048, 200))
kable(df,"latex", align="cr", booktabs = T, linesep = "") %>%
kable_styling() %>%
column_spec(1, width = "3em") %>%
column_spec(2, width = "3em")

kableExtra rmarkdown tables - aligning grouping row labels and footnotes

I am using kableExtra to format some tables in an Rmarkdown document. When running the code below, without any position argument to kable_styling, the grouping row labels (the rows in the table where it says "Group 1" and "Group 2") and the footnotes remain left aligned in relation to the table. This is as I would like it.
```{r cars-table, results='asis'}
kable(mtcars[1:10, 1:2], format = "html", caption = "Group Rows",
col.names = c("MPG[note]", "CYL[note]")) %>%
kable_styling("striped", full_width = F) %>%
group_rows("Group 1", 4, 7) %>%
group_rows("Group 2", 8, 10) %>%
add_footnote(c("Some footnote", "Some other footnote"))
```
But when a position argument is provided to kable_styling, the grouping row labels and footnotes seem to take the opposite alignment, rather than remaining left aligned in relation to the table. I say the opposite alignment, as when I use position = "right", the grouping row labels and footnotes become left aligned.
The code below demonstrates the issue when using position = "left".
```{r cars-table, results='asis'}
kable(mtcars[1:10, 1:2], format = "html", caption = "Group Rows",
col.names = c("MPG[note]", "CYL[note]")) %>%
kable_styling("striped", full_width = F, position = "left") %>%
group_rows("Group 1", 4, 7) %>%
group_rows("Group 2", 8, 10) %>%
add_footnote(c("Some footnote", "Some other footnote"))
```
I only load two libraries to make this example and use the defaults when opening an .Rmd document in RStudio.
library(knitr)
library(kableExtra)
What can I do to make the grouping row labels and footnotes left aligned in relation to the table? Thanks.
In kableExtra 0.3.0 or earlier, there was a bug in the position section of kable_styling. The corresponding CSS for left positioning was mistakenly set as text-align:right... Thank you, #meenaparam, for bringing it up!
Now this bug has been addressed in the current dev version and the CRAN version will be updated in a week.

R kableExtra latex: Add linebreaks to rotated header row

I'm trying to produce table to a Latex-pdf document. I'm using kableExtra and knitr in R.
I have a table that has long column names. When I rotate the header row by 90 degrees linebreaks won't work. Does anyone have an idea how I could achieve both rotated row and linebreaks?
My example is the same as in Hao's Best Practice for newline in Latex table, but I added piped row_spec to the end of the code.
\documentclass[10pt,a4paper]{article}
\usepackage[table]{xcolor}
\begin{document}
\begin{table}
<<global_options, echo=FALSE>>=
library(kableExtra)
library("dplyr")
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
dt_lb %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F,
col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"))) %>%
row_spec(0, angle = 90, align='l', monospace=T)
#
\end{table}
\end{document}
What I get is this, but the [l] tags hint that there's something else wrong with the tags as well:
On StackExchange TEX I found a question about rotation and linebreaks, this is what I'm trying achieve: https://tex.stackexchange.com/questions/14730/big-table-with-rotated-column-labels-using-booktabs
You could use tableHTML:
library(tableHTML)
Replace the new line character "\n" with the HTML tag <br>:
headers <- c("Item\n(Name)", "Value\n(Number)") %>%
stringr::str_replace_all(pattern = "\\n", replacement = "<br>")
Create a tableHTML object and rotate the headers using add_css_header():
dt_lb %>%
tableHTML(rownames = FALSE,
headers = headers,
escape = FALSE,
widths = c(100, 100),
theme = 'scientific') %>%
add_css_header(css = list(c('transform', 'height', 'text-align'),
c('rotate(-45deg)', '70px', 'center')),
headers = 1:2)
The result looks like this:
Note: you can add more css or default themes. Check out the vignettes for more details:
If you want to create a pdf document, you could use RMarkdown:
---
title: "tableHTML2pdf"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
\
```{r}
library(tableHTML)
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
headers <- c("Item\n(Name)", "Value\n(Number)") %>%
stringr::str_replace_all(pattern = "\\n", replacement = "<br>")
dt_lb %>%
tableHTML(rownames = FALSE,
headers = headers,
escape = FALSE,
widths = c(100, 100),
theme = 'scientific') %>%
add_css_header(css = list(c('transform', 'height', 'text-align'),
c('rotate(-45deg)', '70px', 'center')),
headers = 1:2)
```
\
It will then create an HTML file. This file can then be converted to PDF using wkhtmltopdf.
I think you probably rendered your rmarkdown document into HTML... In the rmarkdown yaml header, does it say html_document right now? If so, you can try to change it to pdf_document.....
I rendered a pdf_document with exactly the same code and I think I got what you were looking for...
---
title: "Table Sample"
output: pdf_document
---
``` {r, include = FALSE}
library(tidyverse)
library(kableExtra)
```
```{r}
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
dt_lb %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F,
col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"), align = "c")) %>%
row_spec(0, angle = 90)
```
Latex package makecell was missing.
Hao pointed out that Page 3 of this manual lists some of the necessary Latex packages: haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

Resources