Skip to content

Instantly share code, notes, and snippets.

@tslumley
Created January 4, 2019 01:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tslumley/bf4e195502a00bde6839e5e4d57a6103 to your computer and use it in GitHub Desktop.
Save tslumley/bf4e195502a00bde6839e5e4d57a6103 to your computer and use it in GitHub Desktop.
Shiny app for exploring posterior distributions given surprising data
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Bayesian Surprise"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("obs",
"Observed value",
min = 0,
max = 20,
value = 15),
selectInput(inputId = "prior", label = strong("Prior"),
choices = c("Cauchy","Normal","Laplace","t_5","t_30","logistic"),
selected = "Cauchy"),
selectInput(inputId = "likelihood", label = strong("Likelihood"),
choices = c("Cauchy","Normal","Laplace","t_5","t_30","logistic"),
selected = "Normal")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
XLIM<-20
output$distPlot <- renderPlot({
prior<-(switch(input$prior,
Cauchy=quote(dcauchy(x)),
Normal=quote(dnorm(x)),
Laplace=quote(dexp(abs(x),1)),
t_5=quote(dt(x,5)),
t_30=quote(dt(x,30)),
logistic=quote(dlogis(x))))
likelihood<-(switch(input$likelihood,
Cauchy=quote(dcauchy(input$obs-x)),
Normal=quote(dnorm(input$obs-x)),
Laplace=quote(dexp(abs(input$obs-x),1)),
t_5=quote(dt(input$obs-x,5)),
t_30=quote(dt(input$obs-x,30)),
logistic=quote(dlogis(input$obs-x))))
# generate bins based on input$bins from ui.R
eval(bquote(curve(.(likelihood)*.(prior),from=-2, to=XLIM+2,ylab="Posterior",xlab="x")))
abline(v=0,col="purple",lty=2)
abline(v=input$obs,col="green")
})
}
# Run the application
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment