Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to learn R Shiny in Rstudio. I have used the code below to define the use interface.

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

In the server function, it is always throwing me an error telling lamda not found. So I tried to define lamda as shown below:

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) 

1 Answer

0 votes
by (36.8k points)

I have gone through your code I didn't find any errors. My suggestion is to assign the lambda1 in a global environment. Like this:

lambda1 <<- input$lambda1

Instead of using a package, you can use your own rcoumpound function.

Linke this:

rcompound <- function(n, lambda, rate){

  N <- rpois(n, lambda)

  vapply(N, function(k) sum(rexp(k, rate = rate)), numeric(1))

}

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...