【问题标题】:Embed column with mixed numericInput and selectInput in DT在 DT 中嵌入具有混合 numericInput 和 selectInput 的列
【发布时间】:2021-04-22 17:15:26
【问题描述】:

我想根据变量向接受 selectInput 或 numericInput 的 DT 添加一列。 例如,给定以下 DF:

df1 <- tibble(
 
  var1 = sample(letters[1:3],10,replace = T),
  var2 = runif(10, 0, 2),
  id=paste0("id",seq(1,10,1))
)

DF=gather(df1, "var", "value", -id)

我想在 DF 中创建一个额外的 col(使用 DT),使用 var1 的 selectInput(choices= letters[1:3])和 var2 的 numericInput。 我发现 here 是实现 selectInput 的一个很好的例子,但是我不确定它如何与 numericInput 结合使用。

任何帮助表示赞赏!

【问题讨论】:

    标签: r shiny dt


    【解决方案1】:

    这是this answer的改编版。

    使用pivot_longer 代替gather,这是tidyr 最新版本中推荐的。此外,在为新的 selector 列创建输入时,请检查变量 name。如果是var1,则使用selectInput,否则使用numericInput

    否则,应该以类似的方式工作。

    library(shiny)
    library(DT)
    library(tidyverse)
    
    df1 <- tibble(
      var1 = sample(letters[1:3],10,replace = T),
      var2 = runif(10, 0, 2),
      id=paste0("id",seq(1,10,1))
    )
    
    # gather is retired, switch to pivot_longer
    DF = pivot_longer(df1, cols = -id, names_to = "name", values_to = "value", values_transform = list(value = as.character))
    
    ui <- fluidPage(
      title = 'selectInput or numericInput column in a table',
      DT::dataTableOutput('foo'),
      verbatimTextOutput('sel')
    )
    
    server <- function(input, output, session) {
      for (i in 1:nrow(DF)) {
        if (DF$name[i] == "var1") {
          DF$selector[i] <- as.character(selectInput(paste0("sel", i), "", choices = unique(df1$var1), width = "100px"))
        } else {
          DF$selector[i] <- as.character(numericInput(paste0("sel", i), "", NULL, width = "100px"))
        }
      }
      output$foo = DT::renderDataTable(
        DF, escape = FALSE, selection = 'none', server = FALSE,
        options = list(dom = 't', paging = FALSE, ordering = FALSE),
        callback = JS("table.rows().every(function(i, tab, row) {
            var $this = $(this.node());
            $this.attr('id', this.data()[0]);
            $this.addClass('shiny-input-container');
          });
          Shiny.unbindAll(table.table().node());
          Shiny.bindAll(table.table().node());")
      )
      output$sel = renderPrint({
        str(sapply(1:nrow(DF), function(i) input[[paste0("sel", i)]]))
      })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 2020-03-20
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 2020-09-30
      • 2021-12-12
      • 2023-04-02
      相关资源
      最近更新 更多