I'm trying to include a vertically scrollable table in my html output. The table looks stunning, but I would like to fix the header on top (while right now it scrolls up like everything else). A plus would be being able to filter the columns as well, or interact with them (e.g. sorting).
I have tried using both kable() + kableExtra() and DT(). My understanding is it would be easier with DT, but I find the documentation very confusing.
I'm doing something like this:
library(datasets)
library(knitr)
library(kableExtra)
library(DT)
data(iris)
# with kable
kable(iris, "html") %>%
kable_styling(bootstrap_options = c("striped", "hover", "responsive"),
full_width = F) %>%
scroll_box(width = "100%", height = "400px")
# with DT
datatable(showData, options = list("scrollY"))
I can't really find a way to fix the header on top or add filters. Any tips?
Thanks!
You can combine custom CSS with kable to create a scrollable table body with fixed header.
For example, create file styles.css in project directory with the following content:
.table-fixed-header tbody{
display:block;
overflow:auto;
height:400px;
width:100%;
}
.table-fixed-header thead tr{
display:table-header-group;
height:100%;
}
In YAML of .Rmd document, refer to styles.css:
output:
html_document:
css: styles.css
In R code chunk, pass style name to the kable() function
kable(iris, escape = F, table.attr='class="table-fixed-header"') %>%
kable_styling()
You could've also added
fixed_thead = T
in the scroll box.
Related
I'm unsuccessfully trying to set the font color for flextable generated in r markdown using a css stylesheet.
I can accomplish this when I turn off shadow host, but not with it on. (Just turning it off removes other desirable features.) Here's a short r markdown file demonstrating the difference.
---
title: "Untitled"
output: html_document
---
<style>
div.flextable-shadow-host * {
color: pink;
}
div.tabwid * {
color: pink;
}
</style>
# ignores CSS above
```{r, echo=FALSE}
library(flextable)
flextable(head(mtcars))
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
I want the css external to the r code because I have a button selector on the website the user can change the overall style (e.g., dark mode or not).
When using shadow, the table is assembled outside of HTML. Only the id connects the table to HTML. However, flextable has functions for setting the color. Why not just use one of the many built-in methods to change the color?
For example:
# ignores CSS above
```{r liberator,include=F}
library(flextable)
library(tidyverse)
```
```{r tbler, echo=FALSE}
flextable(head(mtcars)) %>%
color(color = "pink", part = "all")
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
There are many things you can do with flextable styling. You can see more customization options here.
Update: Based on your comments
Okay, this works to change the color of a flextable.
This works if there is only one flextable in the script.
I have the color of the text set to #b21E29 (a shade of red). You can change that as you see fit.
These will SKIP non-shadow flextables
Add this chunk anywhere in your RMD script. This requires no additional libraries or any other customization in your R code.
```{r js_ing,results="asis",engine="js",echo=F}
// extract the styles that are set for the flextable
letMe = document.querySelector('div.flextable-shadow-host').shadowRoot.querySelector('div>style');
// replace color style
// preceding ';' so that 'background-color' doesn't change
letMe.innerHTML = letMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
```
If you have more than one flextable with shadow on, you can use one of the two following chunks instead. In the first--all the same color; in the second--each table has a different color.
These work if there is more than one flextable in the script.
Pay attention to the comments so you can see what to use when depending on your desired output.
All the same color:
```{r moreJs_ing,results="asis",engine="js",echo=F}
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// to set all shadow flextables to the same font color:
for(i = 0, n = letMe.length; i < n; i++){
showMe = letMe[i].shadowRoot.querySelector('div>style');
showMe.innerHTML = showMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
}
```
Each with there own color:
```{r evenMoreJs_ing,results="asis",engine="js",echo=F}
//alternatively to set each to a different color
// make sure you only include one of these options!
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// first table in script
showFirst = letMe[0].shadowRoot.querySelector('div>style');
showFirst.innerHTML = showFirst.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
// second table in script
showSecond = letMe[1].shadowRoot.querySelector('div>style');
showSecond.innerHTML = showSecond.innerHTML.replace(/;(color:.+?);/g, ';color:#003b70 !important;');
// change the indices for each table, keep in mind the first table is [0], not [1]
```
If you aren't sure where you want to go with these, add all three and and include=F as a chunk option to the two you aren't using at that moment in time.
I want to caption the table at the top/bottom of a table. Is there a caption function in the gt package?
gt(head(mtcars)) %>%
tab_header(title="", subtitle="Table 1: Mtcars with gt.") %>%
tab_options(table.width=pct(90),
table.border.top.style=0,
row.padding=px(4)) %>%
tab_style(style=cells_styles(
text_align='left',
text_color='grey'),
locations=cells_title(groups="subtitle"))
I could get the caption argument by installing the development version of the package from Github.
#devtools::install_github("rstudio/gt")
library(gt)
gt(head(mtcars), caption = 'This is table caption') %>%
tab_header(title="A", subtitle="Table 1: Mtcars with gt.")
It seems strange and inconsistent (and annoying!) to not have an alignment option for caption. Especially since gtsummary uses "caption" instead of "title" for table titles.
I found this workaround in another thread (Format caption of gtsummary tables). The idea is to enter the caption as html and do the formatting there.
"<div style='text-align: left; font-weight: bold; color: grey'> Table 1. Patient Characteristics</div>"
Maybe this is just a stupid browser related issue, but ...
I generate some colored tables in a HTML file via Rmarkdown using the tableHTML package (colors are generated by the RColorBrewer package):
```{r Init, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
require(magrittr, quietly = TRUE)
require(tableHTML)
test <- data.frame(A=123, B=456, C=789)
```
...
```{r Test, echo=FALSE, results="asis"}
tableHTML(test) %>%
add_css_thead(css = list('background-color', '#4DAF4A')) %>%
add_css_table(css = list('border', '#4DAF4A'))
```
The colors of the borders look fine in the `Rstudio' viewer:
But the borders are colored different, when opening in Safari or Firefox:
What is the problem with table border colors?
Thank you very much for your question!
With add_css_table, the style is applied to the table-tag and with add_css-thead, it is applied to the thead tag. But I think to get the effect you are looking for, you can apply the styles to the th and td tags via the functions add_css_header and add_css_column:
tableHTML(test) %>%
add_css_header(css = list(c("background-color", "border"),
c("#4DAF4A", "1px solid #4DAF4A")),
headers = 0:4) %>%
add_css_column(css = list("border", "1px solid #4DAF4A"),
columns = c("rownames", names(test)))
In RStudio, it looks like this:
In Firefox:
And in Chrome:
According to https://www.colorhexa.com/4daf4a the closest websafe colour to "#4daf4a" is "#669933". Does changing the border to #669933 solve your problem?
I'm trying to make a 'compact' table in an RMarkdown
I've tried a few things, mostly variations on setting a custom css class and providing the custom css class to a code chunk
I've tried a lot of variations, all of which I can see flow through to the source code (accessed via knitting the html document, opening in chrome, and cmd + opt + u to view source and inspecting the source)
However, I can't work out what's necessary to simply make rows thinner (I believe that's simply reducing cell padding) in a kableExtra table
What I've tried so far
Here's one variation of what I've tried, but the rows are not compact as hoped (they are the standard height)
Which is done with:
---
output: html_document
---
```{r setup, include=FALSE}
library(dplyr); library(kableExtra)
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(dplyr)
library(kableExtra)
```
<style>
pre code, pre, code {
padding: 200 !important;
}
</style>
```{r}
iris %>%
kable %>%
kable_styling("striped", full_width = F) %>%
column_spec(4:5, bold = T) %>%
row_spec(3:5, bold = T, color = "white", background = "#D7261E")
```
but note that the custom css is not taking effect
The easiest way is to override the Bootstrap CSS, decreasing value of padding property (default value is 8px):
<style>
.table>tbody>tr>td{
padding: 1px;
}
</style>
As you pointed out, inspecting the source will lead you to the values above:
You could also do something similar within row_spec(1:nrow(iris), extra_css = "..")
To make the kable rows smaller in a knit to HTML, you can use bootstrap_options = c("condensed") in your kable_styling:
kable_styling(bootstrap_options = c("condensed"))
See https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html
If anyone knows the pdf variant for it, please let me know :)
I'm using the formattable package in R to produce a HTML table. I can use formatter to customise the look of data values in in my table e.g. font-size, color etc. But I can't work out how to alter the appearance of the table header row.I can alter the actual column names using col.names(), but haven't been able to change their appearance.
For example, in the table below how can I change the text color or background color in the header row (mpg, cyl, disp etc.)
Ultimately, I plan to use formattable::as.htmlwidget() and library(webshot) to grab an image file of the table, see
Command for exporting/saving table made with Formattable package in R
Thanks
library(formattable)
formatRed <- formatter("span"
, style = x ~ style(color = ifelse(x > 21 , "red", "black")))
formatSize <- formatter("span"
, style = x ~ style("font-size" = "8px"))
exTb <- formattable(head(mtcars, 5)
, table.attr = "class='table table-striped'"
, list(mpg = formatRed
, wt = formatSize)
)
exTb
You can use a style sheet. You can either embed your style sheet in your .Rmd file, or, you can save your style sheet as a .css file, and then reference it from the .Rmd file. If you want more information about embedding style sheets into your .Rmd file, see this question. If you want more information about referencing an external style sheet, see Section 3.1.4.1. In my example, I'm embedding the style sheet (the <style>...</style> component) in my .Rmd file. My style sheet defines styles to change table headings' fonts to Times New Roman, and table headings' font colours to red.
---
title: "Test"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
<style>
thead {
font-family: "Times New Roman";
color: red;
}
</style>
```{r, echo=FALSE}
library(formattable)
df <- data.frame(Change = c(1), My = c(2), Style = c(3))
ft <- formattable(df)
ft
```
By extending your style sheet, you can impact other elements in the HTML file.