Embed column with mixed numericInput and selectInput in DT

冷暖自知 提交于 2021-02-11 12:29:27

问题


I would like to add a column to a DT that accepts either selectInput or numericInput, depending on the variable. For example, given the following 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)

I would like to create an extra col in the DF (using DT), with selectInput for var1 (choices= letters[1:3]) and numericInput for var2. I have found here a great example for implementing selectInput, however I am not sure how it might be combined with numericInput.

Any help appreciated!


回答1:


Here is an adapted version of this answer.

Instead of gather, using pivot_longer which is recommended in latest version of tidyr. In addition, when creating the inputs for the new selector column, check the variable name. If it is var1 use a selectInput, otherwise use numericInput.

Otherwise, should work in a similar fashion.

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)


来源:https://stackoverflow.com/questions/65773984/embed-column-with-mixed-numericinput-and-selectinput-in-dt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!