在 R 中使用 DT 包进行条件格式化
Conditional Formatting Using DT Package in R
我正在尝试使用 R 中的 DT 包复制 Excel 的条件格式。
在我的示例中,足球俱乐部在下拉列表中被选中,他们的比赛出现在 table 中。我想根据俱乐部的结果突出显示每一行。挑战在于俱乐部在不同的比赛中进行主客场比赛,因此代码需要迎合这一点。行格式应如下所示:
- 绿色代表获胜——如果所选俱乐部的得分比对手多
- 平局为灰色 — 如果所选俱乐部的得分与对手相同
- 红色表示输球——如果所选俱乐部的得分比对手少
这是我目前的代码(格式化在底部)。显然这是错误的,所以不要太在意它。它所做的只是根据 Home.Goals
字段中的特定目标数量突出显示。
output$match_cr <- DT::renderDataTable({
match_cr <- match
# Find home and away matches involving club selected from dropdown.
match_cr <- subset(
match_cr,
match_cr$Home.Club == input$club | match_cr$Away.Club == input$club
)
if (input$season != "All") {
match_cr <- subset(
match_cr,
Season == input$season
)
}
match_cr
DT::datatable(match_cr,filter = 'top', options =
list(lengthMenu = list(c(-1, 10, 50, 100),
list('All', 10, 50, 100)),
pageLength = -1), selection = 'none'
) %>%
formatStyle(
'Home.Goals', target = 'row',
backgroundColor = styleEqual(c(2, 1, 0),c('green', 'grey', 'red'))
)
})
我会在 match_cr
中再添加一列,表明所选俱乐部是否像这样获胜:
match_cr$win.selected = ifelse(((match_cr$Home.Club == input$club) & (match_cr$Home.Goals > match_cr$Away.Goals)) ||
((match_cr$Away.Club == input$club) & (match_cr$Away.Goals > match_cr$Home.Goals)),
2,
ifelse(match_cr$Home.Goals == match_cr$Away.Goals, 1, 0))
您可以在 subset()
之后添加它。然后你可以格式化数据表
formatStyle('win.selected', target = 'row',
backgroundColor = styleEqual(c(2, 1, 0),c('green', 'grey', 'red'))
)
编辑:将 match_cr$
添加到变量名称。
我正在尝试使用 R 中的 DT 包复制 Excel 的条件格式。
在我的示例中,足球俱乐部在下拉列表中被选中,他们的比赛出现在 table 中。我想根据俱乐部的结果突出显示每一行。挑战在于俱乐部在不同的比赛中进行主客场比赛,因此代码需要迎合这一点。行格式应如下所示:
- 绿色代表获胜——如果所选俱乐部的得分比对手多
- 平局为灰色 — 如果所选俱乐部的得分与对手相同
- 红色表示输球——如果所选俱乐部的得分比对手少
这是我目前的代码(格式化在底部)。显然这是错误的,所以不要太在意它。它所做的只是根据 Home.Goals
字段中的特定目标数量突出显示。
output$match_cr <- DT::renderDataTable({
match_cr <- match
# Find home and away matches involving club selected from dropdown.
match_cr <- subset(
match_cr,
match_cr$Home.Club == input$club | match_cr$Away.Club == input$club
)
if (input$season != "All") {
match_cr <- subset(
match_cr,
Season == input$season
)
}
match_cr
DT::datatable(match_cr,filter = 'top', options =
list(lengthMenu = list(c(-1, 10, 50, 100),
list('All', 10, 50, 100)),
pageLength = -1), selection = 'none'
) %>%
formatStyle(
'Home.Goals', target = 'row',
backgroundColor = styleEqual(c(2, 1, 0),c('green', 'grey', 'red'))
)
})
我会在 match_cr
中再添加一列,表明所选俱乐部是否像这样获胜:
match_cr$win.selected = ifelse(((match_cr$Home.Club == input$club) & (match_cr$Home.Goals > match_cr$Away.Goals)) ||
((match_cr$Away.Club == input$club) & (match_cr$Away.Goals > match_cr$Home.Goals)),
2,
ifelse(match_cr$Home.Goals == match_cr$Away.Goals, 1, 0))
您可以在 subset()
之后添加它。然后你可以格式化数据表
formatStyle('win.selected', target = 'row',
backgroundColor = styleEqual(c(2, 1, 0),c('green', 'grey', 'red'))
)
编辑:将 match_cr$
添加到变量名称。