R语言 如何让Shiny App在满足条件时显示结果,否则清除?

wtzytmuj  于 2024-01-03  发布在  其他
关注(0)|答案(1)|浏览(120)

我正在使用一个闪亮的应用程序来运行彩票。我让用户设置种子,并设置两次以确认。我想只有当种子相同时才显示结果。此代码的工作原理是在种子相同之前不显示结果,但我想如果用户后来将种子更改为不相同的任何东西,结果就会消失。我如何才能做到这一点?我尝试观察({})但无法使其工作。
下面是一个示例:

library(dplyr)
library(shiny)

women <- data.frame( id = c(1, 2, 3, 4), firstname = c("Joan", "Robin",  "Anne", "Mary"), lastname = c("Jett", "Reynolds", "Adams", "Martin")) 

shinyApp(

ui<-fluidPage(

    fluidRow(
    column(6, numericInput("num", label = h1("Enter the seed"), value = NA)),
    column(6, numericInput("num2", label = h1("Confirm the seed"), value = NA))
    ),
    fluidRow(verbatimTextOutput("value")),
    fluidRow("These are the women selected in the lottery:", tableOutput("women")),
    ), #CLOSE FLUIDPAGE
server<- function(input, output) {
    output$value <- renderPrint({
    set.seed(input$num) #SET THE SEED
    women_winners<-sample_n(women, 3, replace = FALSE)
    w_output<-subset(women_winners, select=c("firstname", "lastname"))
    #Send the winners' names to be output
    if (input$num==input$num2){ #PUT ALL INSIDE THIS SO IT WON'T RUN UNTIL MET
    output$women <- renderTable(w_output)
    }
    }) 
}, #CLOSE SERVER
)

字符串

qcuzuvrc

qcuzuvrc1#

我相信下面的代码可以满足你的要求。与你的版本相比,我已经将输出对象的构造与显示分离了。这通常是一个很好的实践。
另外,在renderXXX调用中嵌套了输出小部件output$women的创建,我从来没有发现这样做是一件好事,尽管在一些简单的情况下,它不会立即引起问题。
我还添加了对req()的调用,以删除打印到控制台的警告消息。

library(dplyr)
library(shiny)

women <- data.frame( id = c(1, 2, 3, 4), firstname = c("Joan", "Robin",  "Anne", "Mary"), lastname = c("Jett", "Reynolds", "Adams", "Martin")) 

shinyApp(
  ui<-fluidPage(
    fluidRow(
      column(6, numericInput("num", label = h1("Enter the seed"), value = NA)),
      column(6, numericInput("num2", label = h1("Confirm the seed"), value = NA))
    ),
    fluidRow(verbatimTextOutput("value")),
    fluidRow("These are the women selected in the lottery:", tableOutput("women")),
  ), 
  server<- function(input, output) {
    winners <- reactive({
      req(input$num, input$num2)
      
      if (input$num == input$num2) {
        sample_n(women, 3, replace = FALSE)
      }
    })
    
    output$value <- renderPrint({
      winners()
    }) 
  }
)

字符串

相关问题