library(shiny)

ui<-shinyUI(
    fluidPage(
        titlePanel("CI of Population Mean"),
        sidebarLayout(
            sidebarPanel(
                sliderInput("nrep","No. Replicates:",
                            min=1000,max=100000,value=5000,step=100),
                sliderInput("n","Sample Size",min=5,max=100,value=10,step=1),
                sliderInput("cvrg","Coverage Probability",min=.8,max=.99,value=.95,step=.005)
                ),
            mainPanel(
                plotOutput("distPlot")
            )
        )
    )
)

server<-shinyServer(
    function(input, output) {
        output$distPlot <- renderPlot({
            nrep <- input$nrep
            nrep1 <- round(nrep*.6)
            nrep2 <- nrep-nrep1
            n <- input$n
            alpha <- 1- input$cvrg
            ##
            par(mar=c(5,4,3,2)+.1,mex=.6)
            layout(matrix(1:4,2,2),heights=c(1,3))
            ##
            curve(.6*dbeta(x,10,40)+.4*dbeta(x,40,10),ylab="",xlim=c(0,1))
            x <- NULL
            for (i in 1:n) x <- cbind(x,sample(c(rbeta(nrep1,10,40),rbeta(nrep2,40,10))))
            mn <- apply(x,1,mean)
            se <- apply(x,1,sd)
            plot(c(0,0),c(0,21),type="n",xlim=c(0,1),axes=F,xlab="",ylab="")
            for(i in 1:20) {
                lu <- mn[i]-c(-1,1)*se[i]/sqrt(n)*qt(1-alpha/2,n-1)
                lines(lu,c(i,i),lty=1)
                lines(c(lu[1],lu[1]),i+c(-.2,.2),lty=1)
                lines(c(lu[2],lu[2]),i+c(-.2,.2),lty=1)
            }
            abline(v=.44,lty=2)
            ll <- mn-se/sqrt(n)*qt(1-alpha/2,n-1)
            uu <- mn+se/sqrt(n)*qt(1-alpha/2,n-1)
            axis(1,.44,round(mean((ll<=.44)&(uu>=.44)),4))
            ##
            curve(dunif(x),ylab="",xlim=c(0,1))
            x <- NULL
            for (i in 1:n) x <- cbind(x,runif(nrep))
            mn <- apply(x,1,mean)
            se <- apply(x,1,sd)
            plot(c(0,0),c(0,21),type="n",xlim=c(0,1),axes=F,xlab="",ylab="")
            for(i in 1:20) {
                lu <- mn[i]-c(-1,1)*se[i]/sqrt(n)*qt(1-alpha/2,n-1)
                lines(lu,c(i,i),lty=1)
                lines(c(lu[1],lu[1]),i+c(-.2,.2),lty=1)
                lines(c(lu[2],lu[2]),i+c(-.2,.2),lty=1)
            }
            abline(v=.5,lty=2)
            ll <- mn-se/sqrt(n)*qt(1-alpha/2,n-1)
            uu <- mn+se/sqrt(n)*qt(1-alpha/2,n-1)
            axis(1,.5,round(mean((ll<=.5)&(uu>=.5)),4))
        },height=600)
    }
)

shinyApp(ui,server)
