蒙特卡罗模拟的闪亮应用程序

时间:2016-07-21 07:10:58

标签: r shiny montecarlo

我正在尝试在R中为蒙特卡罗模拟构建一个Shiny应用程序。所以我想预测一家公司的收入,这个公司依赖于4个变量A,B,C,D。 我希望用户输入这些变量的最小值和最大值,根据这些值生成统一的随机数,从而计算收入。

请在下面找到我正在使用的代码 -

ui.R

    shinyUI(pageWithSidebar(

      # Application title
      headerPanel("Sales Forecasting using Simulation"),

      sidebarPanel("Input the below values-",
        numericInput("num1", "Min No of A:",100),
        numericInput("num2", "Max No of A:",1000),
        numericInput("num3", "Min B:",49),
        numericInput("num4", "Max B:",99),
        numericInput("num5", "Min C:",2000),
        numericInput("num6", "Max C:",5000),
        numericInput("num7", "Min D:",10),
        numericInput("num8", "Max D:",20)
        ),

      mainPanel("",
                h1("Results for Monte Carlo Simulation"),
                tabsetPanel(
                  tabPanel("Plot", plotOutput("distPlot")), 
                  tabPanel("Summary",  htmlOutput("mytable"))

    ))

    ))

Server.R

    shinyServer(function(input, output) {

      getAFYP_round <- reactive({
        set.seed=12345
        options(scipen = 999)
        AA<-runif(10000, input$num1, input$num2)
        BB<-runif(10000, input$num3, input$num4)
        CC<-runif(10000, input$num5, input$num6)
        DD<-runif(10000, input$num7, input$num8)

        AFYP <- AA*BB*CC*DD

        AFYP_round=round(AFYP, digits = -7)
        AFYP_round
      })

      output$distPlot <- renderPlot({
        options(scipen = 999)
        AFYP_round<-getAFYP_round() 
        zz<-as.data.frame(AFYP_round)
        Freqa=as.data.frame(prop.table(table(AFYP_round)))
        library(dplyr)
        Freqa=Freqa %>% mutate(cumsum = cumsum(Freq))
        library(ggplot2)
        ggplot(Freqa, aes(x=AFYP_round, y=Freq)) +         geom_bar(stat='identity',col="red", fill="yellow") + labs(title="Histogram for Simulation")+labs(x="AFYP", y="Freq")

      })

      output$mytable <- renderUI({
        options(scipen = 999)
        AFYP<-getAFYP_round()
        c1 <- c("Mean", mean(AFYP))
        c2 <- c("Std Dev", sd(AFYP))
        c3 <- c("Minimum", min(AFYP))
        c4 <- c("Maximum", max(AFYP))
        c5 <- c("Maximum", median(AFYP)) 
        c6 <- c("Q(.25)", quantile(AFYP,0.25)) 
        c7 <- c("Q(.75)", quantile(AFYP,0.75))
        c8 <- c("Q(.05)", quantile(AFYP,0.05))
        c9 <- c("Q(.95)", quantile(AFYP,0.95))
        c10 <- c("Q(.025)", quantile(AFYP,0.025))
        c11 <- c("Q(.975)", quantile(AFYP,0.975))

        Summary=rbind(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11)
        ab<-as.data.frame(Summary)
        names(ab)[names(ab)=="V1"] <- "Measures"
        names(ab)[names(ab)=="25%"] <- "Value"
        output$ac <- renderDataTable(ab,options = list(paging = FALSE,searching = FALSE))
        dataTableOutput("ac")

      })

    })

因此,我在代码中遇到以下问题:

  1. 我只能为AA和BB生成随机统一数字。不生成CC和DD,R不会抛出任何错误。
  2. 我想用AFYP_round的频率生成直方图。但R似乎把这个变量视为连续而非离散。
  3. 任何帮助都将受到高度赞赏。

0 个答案:

没有答案