问题描述
我希望在Reactable表的列中添加一个有条件的彩色正方形而不是数字。
例如,如果标志 2,则此表为“绿色”。
带有标志列的可动表
library("tidyverse")
library("reactable")
df <- iris %>%
mutate(Flag = 1:150)
reactable(df[1:4,],columns = list(
Species = colDef(width = 70),# Flag = colDef(width = 50),Flag = colDef(style = function(value) {
if (value > 2) {
my_class <- "Box red"
} else if (value <= 2) {
my_class <- "Box green"
}
# This is wrong
htmltools::div(class = class)
})
))
.row {
display : flex;
align-items : center;
margin-bottom: 15px;
}
.Box {
height: 20px;
width: 20px;
border: 1px solid black;
margin-right : 5px;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
我认为这是一个相关的Reactable example,在单独的文件中有R和css以及条件格式。
R
orders <- data.frame(
Order = 2300:2304,Created = seq(as.Date("2019-04-01"),by = "day",length.out = 5),Customer = sample(rownames(MASS::painters),5),Status = sample(c("Pending","Paid","Canceled"),5,replace = TRUE)
)
reactable(orders,columns = list(
Status = colDef(cell = function(value) {
class <- paste0("tag status-",tolower(value))
htmltools::div(class = class,value)
})
))
css
.tag {
display: inline-block;
padding: 2px 12px;
border-radius: 15px;
font-weight: 600;
font-size: 12px;
}
.status-paid {
background: hsl(116,60%,90%);
color: hsl(116,30%,25%);
}
.status-pending {
background: hsl(230,70%,90%);
color: hsl(230,45%,30%);
}
.status-canceled {
background: hsl(350,90%);
color: hsl(350,30%);
}
但是,我无法通过“状态”列中的彩色椭圆来重现该示例。我不确定如何将R代码与CSS代码相关联。
解决方法
在reference进行条件样式设置和example for custom css之后,我创建了Markdown解决方案。我将class
参数用于整列的CSS类,并将函数应用于style
参数以对每一行进行不同的样式设置。
---
title: "test"
author: "test"
date: "5 9 2020"
output: html_document
---
```{r setup,include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(reactable)
```
```{css,echo=FALSE}
.tag {
display: inline-block;
padding: 2px 12px;
border-radius: 15px;
font-weight: 600;
font-size: 12px;
}
```
```{r}
orders <- data.frame(
Order = 2300:2304,Created = seq(as.Date("2019-04-01"),by = "day",length.out = 5),Customer = sample(rownames(MASS::painters),5),Status = sample(c("Pending","Paid","Canceled"),5,replace = TRUE)
)
reactable(orders,columns = list(
Status = colDef(
class = "tag",style = function(value) {
switch(EXPR = tolower(value),paid = "background: hsl(116,60%,90%); color: hsl(116,30%,25%);",pending = "background: hsl(230,70%,90%); color: hsl(230,45%,30%);",canceled = "background: hsl(350,90%); color: hsl(350,30%);"
)
}
)
))
```