R Shiny 没有响应输入

R Shiny not responding inputs

我在 RStudio 中使用 Shiny,我一直在尝试 运行 此代码:

# Vamos a simular modelos poisson compuestos con diferentes
# distribuciones de severidad.

library(actuar)
library(shiny)

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

    # Número de simulaciones
    headerPanel('Número de simulaciones'),
    numericInput(inputId = "n",label = NULL,
                 value = 10,min = 1,max = 20000),

    # Gráfica S exponencial.
    headerPanel('Exponencial'),
    sidebarPanel(
    sliderInput(inputId = 'lambda1',label = 'Lambda 1',value = 7,
                min = 0, max = 15),
    sliderInput(inputId = 'rate',label = 'rate',value = 5,
                    min = 0, max = 15),
    ),
    mainPanel(
        plotOutput('plot1')
    )

)



# Define server logic required to draw a histogram
server <- function(input, output) {


    output$plot1 <- renderPlot({
        #Preparativos para los gráficos:
        set.seed(20)
        n <- input$n
        lambda1 <- input$lambda1
        rate <- input$rate
        S1 <- rcompound(n = n, #Genera n
                        model.freq = rpois(lambda1), #N~Poi(lambda1)
                        model.sev = rexp(rate = 2)) #Y~Exp(rate)
        MASS::truehist(S1,
                       col=rainbow(125, start = 0.5, 1),
                       main = "exp",nbins = 125)
        abline(h=0,v=0,col="black",lwd=2)
    })

}

# Run the application 
shinyApp(ui = ui, server = server)

我的问题出在服务器功能上,无论我做什么,它一直告诉我找不到 lambda1,但我在 sliderInput 中定义了 lambda1!另一方面,此代码完美运行:

n = 1234
#Exponencial
lambda1 <- 7 ; rate <- 5
S1 <- actuar::rcompound(n = n, #Genera n
               model.freq = rpois(lambda = lambda1), #N~Poi(lambda1)
               model.sev = rexp(rate = rate)) #Y~Exp(rate) 

这是怎么回事?我已经试了好几天了!

我看了一下rcompound的代码,但是没有找到解决这个问题的方法。

一种可能性是将lambda1分配给全局环境:

lambda1 <<- input$lambda1

但这写在全局环境中...

我会简单地使用我自己的 rcompound 函数而不是使用包。这并不复杂:

rcompound <- function(n, lambda, rate){
  N <- rpois(n, lambda)
  vapply(N, function(k) sum(rexp(k, rate = rate)), numeric(1))
}