2

I'm working with Shiny in RStudio and I've been trying to run this code:

# 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)

My problem is in the server function, it doesn't matter what I do, it keeps telling that it doesn't find lambda1, but I define lambda1 in the sliderInput! On the other hand, this code works perfectly:

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) 

Whats going on? I've been trying for days!

1 Answers1

2

I took a look at the code of rcompound but I didn't find how to solve this issue.

A possibility is to assign lambda1 to the global environment:

lambda1 <<- input$lambda1

but this writes in the global environment...

I would simply use my own rcompound function instead of using a package. This is not complicated:

rcompound <- function(n, lambda, rate){
  N <- rpois(n, lambda)
  vapply(N, function(k) sum(rexp(k, rate = rate)), numeric(1))
}
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • It works great! I was clung to the idea of using that package. I'm sorry, I just wanted to know, what is the last "numeric(1)" on the vapply function for? – Edgar Alarcón May 01 '20 at 08:36
  • @EdgarAlarcón `numeric(1)` is a "template" for the output of the function in `vapply`. Here the function returns one number. – Stéphane Laurent May 01 '20 at 08:39