如何使R shiny App中的numericInput()动态化?

8gsdolmq  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(137)

我尝试在R Shiny dynamic中创建一个numericInput()函数。我可以使用selectInput()使此输入动态化并正常工作,但我将其切换到numericInput(),它不再工作。我对numericInput()中的值、最大值和最小值设置感到困惑。基本上,我想知道“研究窗口结束月份”的默认值(winEnd)总是等于mos列的最大值-input$winStart,就像下面的例子和这篇文章底部的代码一样。有什么建议吗?

代码:

library(dplyr)
library(shiny)

testDF <- data.frame(
  mos = as.integer(c(10,6,10,4,8,3)),
  status = as.integer(c(1,1,0,1,1,0))
)

ui <- fluidPage(
  numericInput("winStart","Start month of study window:",value = 0, max = 4, min = 0),
  numericInput("winEnd","End month of study window:", value = 40, max = 40, min = 5),
  h5("Columns `mos` and `status` are original testDF; extra columns added via reactive `tmp()`:"),
  tableOutput("table1")
)

server <- function(input, output, session) {
  
  tmp <- reactive({testDF %>%
      mutate(mos1 = as.integer(pmax(1,mos-input$winStart))) %>%
      mutate(mos2 = pmin(mos1,input$winEnd)) %>%
      mutate(status1 = if_else(mos1 > mos2,as.integer(0),status))
  })
  
  observe({
    updateNumericInput(
      session, 
      "winEnd", 
      value = max(tmp()$mos2), # works fine except end of study window doesn't reflect reductions in start of study window
      # value = max(tmp()$mos - input$winStart), # this doesn't allow you to reduce window end
      max = max(tmp()$mos - input$winStart), 
      min = 5
      )
  })
  
  output$table1 <- renderTable({tmp()})
  
}

shinyApp(ui, server)
tkclm6bt

tkclm6bt1#

问题是您正在更改input$winEndmax值,以匹配最大“mos”,而不是实际的value
既然看起来您只希望input$winEndinput$winStart更改时更新,为什么不将updateNumericInput Package 在observeEvent中,而不仅仅是observe

observeEvent(input$winStart, {
  max_val <- max(tmp()$mos - input$winStart) 
  updateNumericInput(
    session, 
    "winEnd", 
    value = max_val,
    max = max_val, 
    min = 5
  )
})

相关问题