首页 > 解决方案 > 使用 DT 表进行可编辑计算,表内有下拉列表 R 闪亮

问题描述

我已经在 Shiny 中创建了一些 DT 表,其字段直接在 DT 表上输入:

Date_point :我使用 dateInput 输入值

验证:我使用 selectInput 输入值

NMonth :我使用 selectInput 输入值

我有一个问题,我在同一个表输出中有另一列,即“权重”,在单击公式 = 12 / Nmonth 的操作按钮后将重新计算该列,我得到此计算的结果为 NA(警告<observer:observeEvent(input$do)>(... ) : 强制引入的 NA)。预期结果应该是 1 到 12 之间的值,而不是 NA,有没有人知道如何解决这个问题

library(shiny)
library(DT)

ui <- fluidPage(
  
  DT::dataTableOutput('foo'),
  actionButton("do", "Calculate"),
  verbatimTextOutput('sel'),
  verbatimTextOutput('sel2'),
  verbatimTextOutput('date1')
)

server <- function(input, output, session) {
 
  df1 <- reactiveValues(data=NULL)
  data = data.frame(
    Observation = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
    Date_point=c(NA, NA, NA, NA, NA, NA, NA),
    Verification=c(NA, NA, NA, NA, NA, NA, NA),
    NMonth=c(12, 12, 12, 12, 12, 12, 12)
    
  )
  
  data <- data %>%
    mutate(weight = 12/ NMonth)
  
  dat <- reactive({
    data
  })
  
  # adding column having dropdown items
  for (i in 1:nrow(data)) {
    data$Verification[i] <- as.character(selectInput(paste0("sel", i), "", choices = c('(Audited)', '(Unaudited)' ), width = "100px"))
    
  }
  
  for (i in 1:nrow(data)) {
    data$NMonth[i] <- as.character(selectInput(paste0("sel2", i), "", choices = c( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ), width = "100px"))
    
  }
  
  for (i in 1:nrow(data)) {
    data$Date_point[i] <- as.character(dateInput("date1", "Date:", value = "2012-02-29"), width = "100px")
    
  }
  
  observe({
    df1$data <- dat()
  })
  
  ## output for data table
  output$foo = DT::renderDataTable(
    df1$data,
    escape = F,
    editable = T,
    selection = 'none',
    server = F,      # we need it to be TRUE.
    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());")
    ,rownames = F
  )
  
  
  
  
  observeEvent(input$do, {
    info = input$foo_cell_edit
    str(info)
    i = info$row
    j = info$col   
    v = info$value
    df1$data[i, j] <<- DT::coerceValue(v, df1$data[i, j])
    df1$data[,'weight'] <<- 12 / as.numeric(df1$data[,'NMonth'])  
    
    
  })
}

shinyApp(ui, server)

标签: rshinyshinyappsshiny-reactivityshinyjs

解决方案


推荐阅读