使用R的Reactable包和RMarkdown,我想创建一个表,其中一列有一个绿色方块表示状态<= 2,另一个列有一个红色方块。
如果我尝试根据Status列的值设置它的格式,它会创建一个非彩色正方形。请参见图像。

在下面的.Rmd文件中,只有当一列没有值时,我才能让css在该列中生成一个彩色正方形。
总而言之,在Status列下,我想要没有可见数字的彩色方块(绿色方块表示状态<= 2,红色方块表示其他情况),并与列的状态名称左对齐。
Flag列在那里只是为了显示css正在工作。
RMarkdown文件
title: Conditional Colored Square in Reactable Table
author: IX
date: 'September 5, 2020'
slug: test
categories: []
tags: []
output:
html_document
---
```{css, echo=FALSE}.row {
display : flex;align-items : center;margin-bottom: 15px;}
.box {
高度: 20px;
宽度: 20px;
边框: 1px纯黑;
右边距: 5px;
}
.red {
背景色:红色;
}
.green {
背景色:绿色;
}
.blue {
背景颜色:蓝色;
}
```{r, echo=FALSE, message=FALSE, warning=FALSE}库(“reactable”)
orders <- data.frame(
订单= 2300:2304,
Created = seq(as.Date("2019-04-01"),by = "day",length.out = 5),
Customer =sample(行名(MASS::painters),5),
状态= c(1,2,3,4,5),
Flag = c("","")
)
reactable(订单,列=列表(
状态=colDef(单元格=函数(值){
if (value <= 2) { class <- paste0("tag box green", tolower(value)) htmltools::div(class = class, value)}}),
标志=colDef(单元格=函数(值){
class <- paste0("tag box green", tolower(value))htmltools::div(class = class, value)})
))
发布于 2020-09-09 13:45:15
使用css是正确的方法。
由于paste的原因,该颜色不会出现在您提供的示例中
class <- paste0("tag box green", tolower(value))这会导致green1,green2,...是未定义的选择器类。
尝试:
---
title: Conditional Colored Square in Reactable Table
author: IX
date: 'September 5, 2020'
slug: test
categories: []
tags: []
output:
html_document
---
```{css, echo=FALSE}
.row {
display : flex;
align-items : center;
margin-bottom: 15px;
}
.box {
height: 20px;
width: 20px;
border: 1px solid black;
margin-right : 5px;
}
.green {
background: green;
color: green;
}
.red {
background-color: red;
color: red;
}
```
```{r, echo=FALSE, message=FALSE, warning=FALSE}
library("reactable")
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 = c(1, 2, 3, 4, 5),
Flag = c("", "", "","","")
)
reactable(orders, columns = list(
Status = colDef(cell = function(value) {
if (value <= 2) {
class <- "box green"
} else {
class <- "box red"
}
htmltools::div(class = class, "")
}),
Flag = colDef(cell = function(value) {
class <- paste0("tag box")
htmltools::div(class = class, value)
})
))

https://stackoverflow.com/questions/63760660
复制相似问题