【问题标题】:Shiny conditional variable-columns formatting with formatStyle使用 formatStyle 格式化的闪亮条件变量列
【发布时间】:2020-03-11 19:22:04
【问题描述】:

我有一个数据框列表,每个数据框都有一个共同的列名,但其他列可能不同。我的目标是格式化除公共列之外的所有列,因为每个 df 都显示在闪亮的应用程序中。 就我目前为止:

library(shiny)
library(DT)
library(dplyr)

set.seed(101)

df1 <- data.frame(id = runif(10), col1 = rnorm(10), col2 = rnorm(10))
df2 <- data.frame(id = runif(10), col1 = rnorm(10), col3 = rnorm(10))
df3 <- data.frame(id = runif(10), col3 = rnorm(10), col4 = rnorm(10))

df <- list(data1 = df1, data2 = df2, data3 = df3)

ui <- fluidPage(
  fluidRow(
    column(3, selectInput('select', 'Choose dataframe: ', choices = c('data1', 'data2', 'data3'),
                          selected = 1)),
    column(9, DTOutput('table'))
  )
)

server <- function(input, output) {

  selected <- reactive({
    input$select
  })

  col_names <- c('col1', 'col2', 'col3', 'col4')

  output$table <- renderDT(
    df[[selected()]] %>% formatStyle(names(.)[names(.) %in% col_names], backgroundColor = 'yellow'), 
    options = list(pageLength = 15))

}

shinyApp(ui=ui,server=server)

这是我在控制台中遇到的错误:

警告:name2int 中的错误:您指定了列:col1、col2,但数据的列名是 [没有可用的堆栈跟踪]

如何让 formatStyle 与这些变量列名一起使用?

【问题讨论】:

  • 也许用req换行
  • 您能详细说明一下吗?

标签: r shiny


【解决方案1】:

考虑将其更改为datatable

server <- function(input, output) {

  selected <- reactive({
  input$select
  })

  col_names <- c('col1', 'col2', 'col3', 'col4')

  output$table <- DT::renderDT(

    {dat <- df[[selected()]]
    nm1 <- intersect(names(dat), col_names)

    DT::datatable(dat, options = list(pageLength = 15))   %>%
        formatStyle(nm1, backgroundColor = 'yellow')
    }


  )

}

shinyApp(ui=ui,server=server)

-输出

【讨论】:

  • 非常感谢!我之前没有意识到这一点,因为我添加了一个 DataExplorer::drop_columns() 来呈现数据帧而不是数据表。
猜你喜欢
  • 2021-11-21
  • 2016-11-03
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多