Skip to content

Instantly share code, notes, and snippets.

@jknowles
Created January 8, 2013 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jknowles/4484930 to your computer and use it in GitHub Desktop.
Save jknowles/4484930 to your computer and use it in GitHub Desktop.
Simulating fitting a coin and receiving payoffs. A shiny app.
library(shiny)
library(scales)
shinyServer(function(input,output){
trialInput<-reactive(function(){
bias<-input$coin
sims<-input$obs
reps<-input$reps
trials<-rbinom(reps,sims,0.5+bias)
})
output$payoffplot<-reactivePlot(function(){
trials<-trialInput()
df<-data.frame(actor=rep(c("You","Friend"),
each=input$reps),
payout=c(trials*input$value,(input$obs-trials)*input$bet))
p<-qplot(payout,data=df,geom='bar')+facet_wrap(~actor)+coord_flip()+theme_dpi()+
scale_x_continuous(label=dollar)
print(p)
})
output$netplot<-reactivePlot(function(){
trials<-trialInput()
df2<-data.frame(wins=trials,you=trials*input$value,friend=(input$obs-trials)*input$bet)
df2$net<-df2$you-df2$friend
p<-qplot(net,data=df2)+theme_dpi()
print(p)
})
})
library(shiny)
library(ggplot2)
library(eeptools)
shinyUI(pageWithSidebar(
# Title
headerPanel("When is a Fair Coin Fair?"),
sidebarPanel(
helpText('Imagine a friend asks you to bet on the outcome of some coin flips.
You can bet on a series of coin flips at once. Each time the coin is heads,
you receive the payout. Each time the coin is tails, your friend receives
the value of your bet. Explore how the bias of the coin and the value of your
bet and your friend\'s payout explain probability.'),
sliderInput("reps","Number of simulations:",
min=5,max=200,value=100,animate=TRUE),
sliderInput("obs","Number of trials:",
min=50,max=300,value=50),
sliderInput("coin","Fairness of the coin:",
min=-.3,max=.3,value=0,step=0.05),
sliderInput("value","Payout for You",
min=5,max=50,value=5),
sliderInput("bet","Payout for Friend",
min=5,max=50,value=5)
),
# GGPLOT
mainPanel(
h4("Payoffs for You and Your Friend"),
plotOutput("payoffplot"),
h4("Your Net Wins"),
plotOutput("netplot")
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment