如何在闪亮的 react() 函数中存储 Monte Carlo 模拟输出

How to Store Monte Carlo Simulation Outputs Within a reactive() Function In Shiny

我一直在从事一个附带项目,该项目涉及一个简单的闪亮应用程序,该应用程序允许用户输入棋盘游戏的掷骰子参数,然后让代码使用这些参数预制 10,000 次掷骰子并显示平均值劳斯莱斯。我有一个成功实现这一目标的基本代码,但我正在努力如何将它变成一个闪亮的应用程序以供其他人访问。

我面临的问题是,在闪亮代码的服务器部分,我不知道如何将中间结果存储在单个 reactive() 函数中。是否有与重复功能一起使用的本地存储选项?

我使用的代码是:

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("10,000 Roll Simulator"),

   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
         numericInput(inputId = "num_tac", label = "TAC", 
                      value =1 , min = 1, max = 20),
         numericInput(inputId = "num_def", label = "DEF", 
                      value =1 , min = 1, max = 10),
         numericInput(inputId = "num_arm", label = "ARM", 
                      value =0 , min = 0, max = 10)
      )
   )
)

server <- function(input, output){
 data()<- reactive({
   One_roll<- function(){dice <- sample(1:6, size = input$num_tac, replace = TRUE)
   return(sum((dice >= input$num_def)-input$num_arm))
   sims<-replicate(10000, One_roll()}
output$stats <- renderPrint({mean(data())})
}
# Run the application 
shinyApp(ui = ui, server = server)

任何帮助将不胜感激,谢谢!

您的代码存在一些问题:

  • data()<- 是不允许的。使用 data<- 而不是 data()

  • 在函数内部使用input$绝对不是传递参数的正确方式

这是一个修改后的服务器函数,其中 One_roll 函数在反应式外部定义,但在内部调用,输入作为参数传递:

server <- function(input, output){
  One_roll<- function(num_tac,num_def,num_arm){
    dice <- sample(1:6, size = num_tac, replace = TRUE)
    sum((dice >= num_def)-num_arm)
  }
  data<- reactive(replicate(10000, One_roll(input$num_tac,input$num_def, input$num_arm )))
  output$stats <- renderPrint(mean(data()))
}

并且您还需要 textOutputui 函数中调用 renderText 例如:

ui <- fluidPage(

  # Application title
  titlePanel("10,000 Roll Simulator"),

  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      numericInput(inputId = "num_tac", label = "TAC", 
                   value =1 , min = 1, max = 20),
      numericInput(inputId = "num_def", label = "DEF", 
                   value =1 , min = 1, max = 10),
      numericInput(inputId = "num_arm", label = "ARM", 
                   value =0 , min = 0, max = 10)
    ), mainPanel = textOutput("stats")
  )
)

也可以先将所有用户输入的数据保存到一个静态变量中,然后作为普通变量使用。

server <- function(input, output) {

temp <- reactive({

  tac <- input$num_tac

  def <- input$num_def

  arm <- input$num_arm

  One_roll <- function(tac, def, arm) {

    dice <- sample(1:6, size = tac, replace = TRUE)

    sum((dice >= def) - arm)

  }

  data <- replicate(10000, One_roll(tac, def, arm))

  #remember to print the data again so the results will be saved to temp

  data

})

output$stats <- renderPrint({

  mean(temp())

})

}