Cannot completely remove reactable column with CSS class - css

I've created a table using reactable with Quarto Markdown in RStudio and I'm attempting to use a CSS class to remove one column (Twitter) when the screen width is 700px or less (mobile devices). I'm using "visibility: hidden" in my CSS to remove the column, however this is only removing the column contents and not the column header nor the column itself. I'm left with an empty column with the column title displayed. I need the column completely removed.
Here is my R code to create the table:
library(reactable)
library(crosstalk)
library(htmltools)
note_taking <- read.csv("data.csv")
tbl <- reactable(
data,
defaultPageSize = 15,
showPageSizeOptions = TRUE,
wrap = TRUE,
defaultColDef = colDef(headerClass = "header",
),
rowStyle = list(cursor = "pointer"),
theme = reactableTheme(
borderColor = "#e9f3fd",
highlightColor = "rgba(233, 243, 253, .8)",
),
columns = list(
Twitter = colDef(html=TRUE, cell = function(value) {
url <- paste0("https://twitter.com/", value)
tags$a(href = url, target = "_blank", paste0("#", value))
},
class = "twitter-col", width = 150
),
))
tbl
Here is my CSS class:
#media only screen and (max-width: 700px) {
.twitter-col {
visibility: hidden;
}}
I've tried changing the column width to 0 but it has no effect. Any help is appreciated.

Based on reactable docs. You can apply additional CSS classes to the header using headerClass. Add twitter-col-header class into Twitter column header. Then instead of using visibility: hidden, use the display: none instead on all the columns (including column header and column cells)
Add headerClass = "twitter-col-header" to colDef function
Add Css rule for both for the header and the cell columns
library(reactable)
library(crosstalk)
library(htmltools)
note_taking <- read.csv("data.csv")
tbl <- reactable(
data,
defaultPageSize = 15,
showPageSizeOptions = TRUE,
wrap = TRUE,
defaultColDef = colDef(headerClass = "header",
),
rowStyle = list(cursor = "pointer"),
theme = reactableTheme(
borderColor = "#e9f3fd",
highlightColor = "rgba(233, 243, 253, .8)",
),
columns = list(
Twitter = colDef(html=TRUE, cell = function(value) {
url <- paste0("https://twitter.com/", value)
tags$a(href = url, target = "_blank", paste0("#", value))
},
class = "twitter-col", width = 150,
headerClass = "twitter-col-header"
),
))
tbl
#media only screen and (max-width: 700px) {
.twitter-col,
.twitter-col-header {
display: none;
}
}

Related

Flexdashboard checkbox flows off page

I created a datatable in a flexdashboard with a checkbox, but the checkbox flows off the page. I tried to adjust the padding {data-padding = 10} but nothing changed. Below is the code and a picture of what the dashboard looks like. How do I move everything to the right so that it's aligned with the title of the page?
---
title: "School Dashboard"
author: "Shannon Coulter"
output:
flexdashboard::flex_dashboard:
orientation: rows
social: menu
source_code: embed
theme: spacelab
---
```{r}
library(tidyverse)
library(crosstalk)
library(DT)
library(flexdashboard)
```
Student Lookup
================================================================================
### Chronic Absenteeism Lookup
```{r ca-lookup, echo=FALSE, message=FALSE, warning=FALSE}
ican_tab <- tibble(
year = c("2022", "2022", "2022", "2022", "2022"),
date = c("March", "March","March","March","March"),
school = c("ABC", "CDE","ABC","DEF","GHI"),
grade = c("6th", "7th","8th","4th","5th"),
race_eth = c("White", "Hispanic","White","Filipino","White"),
abs_levels = c("Not At-Risk of Chronic Absenteeism", "At-Risk of Chronic Absenteeism",
"Severe Chronic Absenteeism", "Severe Chronic Absenteeism",
"Moderate Chronic Absenteeism")
)
sd <- SharedData$new(ican_tab)
bscols(list(
filter_checkbox("abs_levels", "Level", sd, ~ abs_levels, inline = TRUE),
datatable(
sd,
extensions = c("Buttons",
"Scroller"),
options = list(
autoWidth = TRUE,
scrollY = F,
columnDefs = list(list(
className = 'dt-center',
targets = c(2, 3, 4, 5)
)),
lengthMenu = c(5, 10, 25, 100),
dom = "Blrtip",
deferRender = TRUE,
scrollY = 300,
scroller = TRUE,
buttons = list('copy',
'csv',
'pdf',
'print')
),
filter = "top",
style = "bootstrap",
class = "compact",
width = "100%",
colnames = c(
"Year",
"Date",
"School",
"Grade",
"Race",
"Level"
)
) %>%
formatStyle('abs_levels',
backgroundColor = styleEqual(
unique(ican_tab$abs_levels),
c(
"#73D055ff",
"#95D840FF",
"#B8DE29FF",
"#DCE319FF"
)
))
))
```
[![enter image description here][1]][1]
The easiest way to address this is probably to add style tags to your dashboard. You can put this anywhere. I usually put it right after the YAML or right after my first R chunk, where I just place my knitr options and libraries. This does not go inside an R chunk.
<style>
body { /*push content away from far right and left edges*/
margin-right: 2%;
margin-left: 2%;
}
</style>
Update based on your updated question and comments
I don't have the content around your table, so I will give you a few options that work. For the most part, any one option won't be enough. You can mix and match the options that work best for you.
This is what I've got for the original table:
Option 1: you can use CSS to push the table away from the edges (as in my original response
Option 2: change the font sizes
Option 3: constrain the size of the datatable htmlwidget
Option 4: manually make the columns narrower
Option 5: alter the filter labels (while keeping the same filters and data)
Aesthetically looks the best? It depends on what else is on the dashboard.
I think you will need the original CSS (option 1, in my original answer) regardless of what other options you choose to use.
Option 1 is above
Option 2
To change the font sizes, you have to modify the filter_checkbox and the datatable after they're made. Instead of presenting all of the programming code, I'm going to show you want to add or modify and how I broke down the objects.
Your original code for filter_checkbox remains the same. However, you'll assign it to an object, instead of including it in bscols.
Most of the code in your datatable will remain the same. there is an addition to the parameter options. I've included the original and change for that parameter.
# filter checkbox object
fc = filter_checkbox(...parameters unchanged...)
fc$attribs$style <- css(font.size = "90%") # <-change the font size
dt = datatable(
...
...
options = list( # this will be modified
autoWidth = TRUE, # <- same
scrollY = F, # <- same
initComplete = JS( # <- I'M NEW! change size of all font
"function(settings, json) {",
"$(this.api().table().container()).css({'font-size': '90%'});",
"}"),
columnDefs = list( # <- same
list(className = 'dt-center', targets = c(2, 3, 4, 5))),
...
... # remainder of datatable and formatStyles() original code
)
# now call them together
bscols(list(fc, dt))
The top version is with 90% font size, whereas the bottom is the original table.
Option 3
To constrain the size of the datatable widget, you'll need to create the object outside of bscols, like I did in option 2. If you were to name your widget dt as in my example, this is how you could constrain the widget size. This example sets the datatable to be 50% of the width and height viewer screen (or 1/4 of the webpage). Keep in mind that the filters are not part of the widget, so in all, the table is still more than 1/4th of the webpage. You will have to adjust the size for your purposes, of course. I recommend using a dynamic sizing mechanism like vw, em, rem, and the like.
dt$sizingPolicy$defaultWidth <- "50vw"
dt$sizingPolicy$defaultHeight <- "40vh"
The top image has options 1, 2, and 3; the bottom is the original table.
Option 4
To modify the width of the columns, you can add this modification to the parameter options in you call to datatable. This could be good, because most of the columns don't require as much width as the last column. However, if you change the font size or scale the table, it will change the font size dynamically, so this option may not be necessary.
Despite using em here, in the course of this going from R code to an html_document, it was changed to pixels. So this is not dynamically sized. (Not a great idea! Sigh!)
columnDefs = list(
list(className = 'dt-center', targets = c(2, 3, 4, 5)),
list(width = '5em', targets = c(1,2,3,4,5))), # <- I'm NEW!
Option 5
For this option, I took the programming behind crosstalk::filter_checkbox() and modified the code a bit. I changed the function to filter_checkbox2(). If you use it, you can render it both ways and just keep the one you like better.
This first bit of code is the three functions that work together to create a filter_checkbox object with my modifications so that you can have a label that isn't exactly the same as the levels.
It's important to note that the filters are alphabetized by datatable. It doesn't matter if they're factors, ordered, etc. If you use this new parameter groupLabels, they need to be in an order that aligns with the levels when they're alphabetized.
I put this code in an include=F chunk by itself:
# this is nearly identical to the original function
filter_checkbox2 = function (id, label, sharedData, group,
groupLabels = NULL, # they're optional
allLevels = FALSE, inline = FALSE, columns = 1) {
options <- makeGroupOptions(sharedData, group,
groupLabels, allLevels) # added groupLabels
labels <- options$items$label
values <- options$items$value
options$items <- NULL
makeCheckbox <- if (inline)
inlineCheckbox
else blockCheckbox
htmltools::browsable(attachDependencies(tags$div(id = id,
class = "form-group crosstalk-input-checkboxgroup crosstalk-input",
tags$label(class = "control-label", `for` = id, label),
tags$div(class = "crosstalk-options-group",
crosstalk:::columnize(columns,
mapply(labels, values, FUN = function(label, value) {
makeCheckbox(id, value, label)
}, SIMPLIFY = FALSE, USE.NAMES = FALSE))),
tags$script(type = "application/json", `data-for` = id,
jsonlite::toJSON(options, dataframe = "columns",
pretty = TRUE))),
c(list(crosstalk:::jqueryLib()),crosstalk:::crosstalkLibs())))
}
inlineCheckbox = function (id, value, label) { # unchanged
tags$label(class = "checkbox-inline",
tags$input(type = "checkbox",
name = id, value = value),
tags$span(label))
}
# added groupLabels (optional)
makeGroupOptions = function (sharedData, group, groupLabels = NULL, allLevels) {
df <- sharedData$data(withSelection = FALSE, withFilter = FALSE,
withKey = TRUE)
if (inherits(group, "formula"))
group <- lazyeval::f_eval(group, df)
if (length(group) < 1) {
stop("Can't form options with zero-length group vector")
}
lvls <- if (is.factor(group)) {
if (allLevels) {levels(group) }
else { levels(droplevels(group)) }
}
else { sort(unique(group)) }
matches <- match(group, lvls)
vals <- lapply(1:length(lvls), function(i) {
df$key_[which(matches == i)]
})
lvls_str <- as.character(lvls)
if(is.null(groupLabels)){groupLabels = lvls_str} # if none provided
if(length(groupLabels) != length(lvls_str)){ # if the # labels != the # groups
message("Warning: The number of group labels does not match the number of groups.\nGroups were used as labels.")
groupLabels = lvls_str
}
options <- list(items = data.frame(value = lvls_str, label = groupLabels, # changed from lvls_str
stringsAsFactors = FALSE), map = setNames(vals, lvls_str),
group = sharedData$groupName())
options
}
When I used this new version of I changed label = "Level" to label = "Chronic Absenteeism Level". Then removed " Chronic Absenteeism" from the filter labels. The data and the datatable does not change, just the filter checkbox labels.
filter_checkbox2("abs_levels", "Chronic Absenteeism Level",
sd, ~ abs_levels, inline = TRUE,
groupLabels = unlist(unique(ican_tab$abs_levels)) %>%
str_replace(" Chronic Absenteeism", "") %>% sort())
The first image is your table with options 1, 2, 3, and 5 (not 4).
The top version in the next image has options 1, 2, 3, and 5 (not 4). The bottom is the original table. After that
If I've left anything unclear or if have any other questions, let me know.

How to style reactable cell background with custom grouping select

I have some data I'm trying to present using reactable. I am styling the background of cells based on the value. There are a number of groups in the data which are useful, but the groups themselves do not have an aggregated value that is useful.
The issue I'm facing is that when the data is grouped with the custom grouping select, the table will retain the style of the first few rows of data so the background is coloured. I would like it to be blank for the grouped row.
In the example below, when grouping by group you'll notice that A and C have the background coloured, inheriting the style from rows 1 and 3 in the data. I could imagine a hacky way of organizing the data so only non-stylized rows come first, but that is not really appropriate as the data would be too disorganized at initial presentation.
Is there a way to strip the style when grouped, but retain it for the rows with values?
library(reactable)
library(htmltools)
set.seed(1)
data <- data.frame(
group = rep(c("A", "B", "C"), each = 5),
value = rnorm(15)
)
htmltools::browsable(
tagList(
div(tags$label("Group by", `for` = "tab")),
tags$select(
id = "tab",
onchange = "Reactable.setGroupBy('tab', this.value ? [this.value] : [])",
tags$option("None", value = ""),
tags$option("Group", value = "group"),
),
reactable(
data,
columns = list(
value = colDef(style = function(value){
if (value < 0) list(background = "#ffa500")
})
),
defaultPageSize = 15,
elementId = "tab"
)
)
)
I found a way using JavaScript. I've changed the variable value to num in the example below so it's more clear how to apply the function.
The grouping is done via JavaScript in the browser, so there isn't a way to control group styling in R as far as I'm aware.
library(reactable)
library(htmltools)
set.seed(1)
data <- data.frame(
group = rep(c("A","B","C"), each = 5),
num = rnorm(15)
)
htmltools::browsable(
tagList(
div(tags$label("Group by", `for` = "tab")),
tags$select(
id = "tab",
onchange = "Reactable.setGroupBy('tab', this.value ? [this.value] : [])",
tags$option("None", value = ""),
tags$option("Group", value = "group"),
),
reactable(
data,
columns = list(
num = colDef(style = JS("function(rowInfo) {
var value = rowInfo.row['num']
if (value < 0) {
var background = '#ffa500'
}
return {background: background}
}"))
),
defaultPageSize = 15,
elementId = "tab"
)
)
)

R reactable - applying multiple styles in colDef

Columns in reactable (R package reactable) can be styled with a list of styles, a function or javascript - which works if I want to use one way only. How can these be combined (without rewriting the list, function or javascript code?
Example:
library(reactable)
list_style <- list(background = "#eee")
js_style <- JS("
function(rowInfo) {
return {fontWeight: 'bold' }
}
")
fn_style <- function(value) {
color <- "#008000"
list(color = color)
}
df <- data.frame(x = 1:10, y = 11:20)
reactable(
df,
columns = list(
x = colDef(
style = c(list_style, js_style, fn_style) # This generates the below error
)
)
)
Error:
Error in colDef(style = c(list_style, js_style, fn_style)) :
`style` must be a named list, character string, JS function, or R function
reactable(
df,
columns = list(
x = colDef(
style = list(list_style, js_style, fn_style)
)
)
)
it seems that your style out of list, please replace those code with this reactable

How to change the color background of a box (level 3 header/building block of flexdashboard)?

I'm trying to build an HTML dashboard with multiple pages and all sorts of different elements using gauges, tables, charts from highcharter package, charts from ggplot2 package, images, etc.
I'm trying to change the background color of some elements. I've tried doing this using the built-in arguments of charts and tables, I've tried using div and setting style=background-color: #dddddd (Hex code for the grey I'm trying to use) and I've tried playing around with CSS style with something like:
<style type="text/css">
.chart-title { /* chart_title */
background-color: #dddddd;
</style>
However, I'm not familiar with CSS and couldn't find the correct substitution to ".chart-title" to get what I need. I tried using "body", "h3", "header", "box". I managed to change some colors but not where I needed them to change.
I pasted below a piece of my Dashboard and corresponding Print Screen of the result.
HOME
=======================================================================
Row {data-height=400}
-------------------------------------------------------------------------------------------------------------
### Productivity {.no-title}
```{r fig.width=1.5}
df1<-data.frame(Factory = c('<img src="seta4.png" height=60></img>', "150t/h"))
div(datatable(df1, rownames=FALSE, options = list(ordering=FALSE, scrollY = "150px", scrollX=FALSE, dom='t', autowidth=TRUE,
#columnDefs = list(list(width='5px', targets=c(1,2,3))),
columnDefs=list(list(className='dt-center', targets=c(0)))), escape = FALSE) %>%
formatStyle(names(df1), textAlign = 'center' ) %>%
formatStyle(names(df1), backgroundColor='rgb(221,221,221)', color='rgb(0,0,0)') %>%
formatStyle(names(df1), `font-size` ='15px'),
style="font-size:12px; font-weight:Bold; background-color: #dddddd")
```
### Occupation {.no-title}
```{r fig.width=2}
rate <- ocupacao[1]
div(gauge(rate, min = 0, max = 100, symbol = '%', gaugeSectors(
success = c(0, 39), warning = c(40, 79), danger = c(80, 100)
)), style="background-color: #dddddd")
```
### Ferro {.no-title}
```{r fig.width=3}
df1<-data.frame(Ferroviario = c('<img src="trem.png" height=60></img>', "30Kt"))
div(datatable(df1, rownames=FALSE, options = list(ordering=FALSE, scrollY = "150px", scrollX=FALSE, dom='t', autowidth=TRUE,
#columnDefs = list(list(width='5px', targets=c(1,2,3))),
columnDefs=list(list(className='dt-center', targets=c(0)))), escape = FALSE) %>%
formatStyle(names(df1), textAlign = 'center' ) %>%
formatStyle(names(df1), backgroundColor='rgb(221,221,221)', color='rgb(0,0,0)') %>%
formatStyle(names(df1), `font-size` ='15px'),
style="background-color: #dddddd; font-size:12px, font-weight:Bold")
```
Dashboard:
As you can see, I'm not getting the result I wanted. I wanted the boxes in the top row to have all grey backgrounds, but the most I can get is that only part of the background is grey and the edges/remaining parts are still white.
Is there any way to do this?

How to preselect a variable value of column or row variables in HTML widget rpivotTable?

I am using the very interesting html widget rpivotTable. I know how to preselect variables that are added as rows or columns to the pivottable, but what I really need is a preselection of certain values of these variables.
As an example of what I mean I use the code from the vignette page:
library(rpivotTable)
data(HairEyeColor)
rpivotTable(
data = HairEyeColor, rows = "Hair",cols = "Eye", vals = "Freq",
aggregatorName = "Sum", rendererName = "Table",
sorters = "function(attr) {
var sortAs = $.pivotUtilities.sortAs;
if (attr == \"Hair\"){
return sortAs([\"Red\", \"Brown\", \"Blond\", \"Black\"]);}
}", width = "100%", height = "400px"
)
If I want, e.g. to preselect the value "Red" of the "Hair" variable, is it possible to do that in this script? Something like:
library(rpivotTable)
data(HairEyeColor)
rpivotTable(
data = HairEyeColor, rows = "Hair",cols = "Eye", vals = "Freq",
aggregatorName = "Sum", rendererName = "Table", sorters = "
function(attr) {
var sortAs = $.pivotUtilities.sortAs;
if (attr == \"Hair\") { return select([\"Red\"]); }
}", width = "100%", height = "400px"
)
I know this doesn't work but is it the way to go?
Yes, if I understand correctly, this can be accomplished with inclusions and exclusions. The format is a little funky though and requires everything to be a list.
library(rpivotTable)
data(HairEyeColor)
rpivotTable(
data = HairEyeColor,
rows = "Hair",
cols="Eye",
vals = "Freq",
aggregatorName = "Sum",
rendererName = "Table",
inclusions = list(
"Hair" = list("Red")
)
)

Resources