我正在尝试使用 DT 包中的数据表创建一个 Shiny 的应用程序。 每当表中的字段为 NA/空白时,我想用红色突出显示它。
我使用部分虹膜数据集并创建了一些 NA 值创建了一个可重现的示例。
# Loading iris dataset, shortening and creating NA in ‘Sepal.Length‘ variable
data(iris)
iris
df <- iris[c(1:10),]
df[c(5:10),1] <- NA
library(shiny)
library(DT)
ui <- fluidPage(
dataTableOutput(outputId = "output_1")
)
server <- function(input, output) {
output$output_1 <- renderDataTable(server=FALSE, datatable({
iris %>% filter(Petal.Length>1.4) %>% formatStyle(
'largest_dimension',
background = styleColorBar(is.na(df$Sepal.Length), "red"),
backgroundSize = '100%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center'
)},
extensions = 'Buttons',
options = list(
pageLength=10,
lengthMenu=c(10,20,50,100),
paging = TRUE,
searching = TRUE,
fixedColumns = TRUE,
autoWidth = TRUE,
ordering = TRUE,
dom = 'Blfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
),
class = "display"))
}
shinyApp(ui = ui, server = server)
但是,该代码不起作用。我收到以下错误: 警告:formatColumns 错误:表参数无效;预期是从 datatable() 创建的表对象 106:%>% 103: 表达式函数 102:widgetFunc 101: htmlwidgets::shinyRenderWidget 100: 函数 87: 渲染函数 86: 渲染函数 82: 渲染函数 81: 输出$output_1 1:运行应用程序
有人可以帮忙吗?
最佳答案
你的语法错误。数据表生成如下:
library(DT)
df <- iris[c(1:10),]
df[c(5:10),1] <- NA
datatable(
df,
options = list(
......
)
) %>%
formatStyle("Sepal.Length", backgroundColor = styleEqual(NA, "red"))
然后你必须做
output[["output_1"]] <- renderDT({
datatable(
df,
options = list(
......
)
) %>%
formatStyle("Sepal.Length", backgroundColor = styleEqual(NA, "red"))
}, server = FALSE)
关于r - renderDataTable 中的 formatStyle Shiny ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69376917/