Skip to content

Instantly share code, notes, and snippets.

@calpolystat
Last active March 15, 2018 18:29
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 calpolystat/d896c5848934484181be to your computer and use it in GitHub Desktop.
Save calpolystat/d896c5848934484181be to your computer and use it in GitHub Desktop.
LCO CI Generator: Shiny app at http://www.statistics.calpoly.edu/shiny, LCO website at http://www.calpoly.edu/~jdoi/LCO
LCO CI Generator Shiny App
Base R code created by Jimmy Doi
Shiny app files created by Jimmy Doi
Cal Poly Statistics Dept Shiny Series
http://statistics.calpoly.edu/shiny
Title: LCO CI Generator
Author: Jimmy Doi
AuthorUrl: http://www.calpoly.edu/~jdoi
License: MIT
DisplayMode: Normal
Tags: LCO CI Generator
Type: Shiny
##################################################
# R code written by: #
# #
# Jimmy A. Doi (jdoi@calpoly.edu) #
# Department of Statistics #
# Cal Poly State Univ, San Luis Obispo #
# Web: www.calpoly.edu/~jdoi #
# #
# ............................................ #
# #
# If using please cite: #
# #
# Schilling, M., Doi, J. #
# "A Coverage Probability Approach to Finding #
# an Optimal Binomial Confidence Procedure", #
# The American Statistician, 68, 133--145 #
# #
# ............................................ #
# #
# Shiny app site: jdoi.shinyapps.io/LCO-CI #
# #
# ............................................ #
# #
# Code updated on: 1AUG2014 #
##################################################
##############################################################################
# The function LCO.CI() generates the LCO confidence intervals #
# for X = 0, 1, ..., n for a specified n and confidence level. #
# #
# Example: To generate all LCO confidence intervals at n=20, #
# level=.90, and 3rd decimal place accuracy, use #
# #
# > LCO.CI(20,.90,3) #
##############################################################################
LCO.CI <- function(n,level,dp)
{
# For desired decimal place accuracy of dp, search on grid using (dp+1)
# accuracy then round final results to dp accuracy.
iter <- 10**(dp+1)
p <- seq(0,.5,1/iter)
############################################################################
# Create initial cpf with AC[l,u] endpoints by choosing coverage
# probability from highest acceptance curve with minimal span.
cpf.matrix <- matrix(NA,ncol=3,nrow=iter+1)
colnames(cpf.matrix)<-c("p","low","upp")
withProgress(message = "Computing intervals ...", style = "notification", value = 0.2, {
for (i in 1:(iter/2+1)){
if (i==((iter/2)/4)) incProgress(0.2)
if (i==((2*iter/2)/4)) incProgress(0.2)
if (i==((3*iter/2)/4)) incProgress(0.2)
p <- (i-1)/iter
bin <- dbinom(0:n,n,p)
x <- 0:n
pmf <- cbind(x,bin)
# Binomial probabilities ordered in descending sequence
pmf <- pmf[order(-pmf[,2],pmf[,1]),]
pmf <- data.frame(pmf)
# Select the endpoints (l,u) such that AC[l,u] will
# be at least equal to LEVEL. The cumulative sum of
# the ordered pmf will identify when this occurs.
m.row <- min(which((cumsum(pmf[,2])>=level)==TRUE))
low.val <-min(pmf[1:m.row,][,1])
upp.val <-max(pmf[1:m.row,][,1])
cpf.matrix[i,] <- c(p,low.val,upp.val)
# cpf flip only for p != 0.5
if (i != iter/2+1){
n.p <- 1-p
n.low <- n-upp.val
n.upp <- n-low.val
cpf.matrix[iter+2-i,] <- c(n.p,n.low,n.upp)
}
}
############################################################################
# LCO Gap Fix
# If the previous step yields any violations in monotonicity in l for
# AC[l,u], this will cause a CI gap. Apply fix as described in Step 2 of
# algorithm as described in paper.
# For p < 0.5, monotonicity violation in l can be determined by using the
# lagged difference in l. If the lagged difference is -1 a violation has
# occurred. The NEXT lagged difference of +1 identifies the (l,u) pair to
# substitute with. The range of p in violation would be from the lagged
# difference of -1 to the point just before the NEXT lagged difference of
# +1. Substitute the old (l,u) with updated (l,u) pair. Then make required
# (l,u) substitutions for corresponding p > 0.5.
# Note the initial difference is defined as 99 simply as a place holder.
diff.l <- c(99,diff(cpf.matrix[,2],differences = 1))
if (min(diff.l)==-1){
for (i in which(diff.l==-1)){
j <- min(which(diff.l==1)[which(diff.l==1)>i])
new.low <- cpf.matrix[j,2]
new.upp <- cpf.matrix[j,3]
cpf.matrix[i:(j-1),2] <- new.low
cpf.matrix[i:(j-1),3] <- new.upp
}
# cpf flip
pointer.1 <- iter - (j - 1) + 2
pointer.2 <- iter - i + 2
cpf.matrix[pointer.1:pointer.2,2]<- n - new.upp
cpf.matrix[pointer.1:pointer.2,3]<- n - new.low
}
incProgress(0.2)
############################################################################
# LCO CI Generation
ci.matrix <- matrix(NA,ncol=3,nrow=n+1)
rownames(ci.matrix) <- c(rep("",nrow(ci.matrix)))
colnames(ci.matrix) <- c("x","lower","upper")
# n%%2 is n mod 2: if n%%2 == 1 then n is odd
# n%/%2 is the integer part of the division: 5/2 = 2.5, so 5%/%2 = 2
if (n%%2==1) x.limit <- n%/%2
if (n%%2==0) x.limit <- n/2
for (x in 0:x.limit)
{
num.row <- nrow(cpf.matrix[(cpf.matrix[,2]<=x & x<=cpf.matrix[,3]),])
low.lim <-
round(cpf.matrix[(cpf.matrix[,2]<=x & x<=cpf.matrix[,3]),][1,1],
digits=dp)
upp.lim <-
round(cpf.matrix[(cpf.matrix[,2]<=x & x<=cpf.matrix[,3]),][num.row,1],
digits=dp)
ci.matrix[x+1,]<-c(x,low.lim,upp.lim)
# Apply equivariance
n.x <- n-x
n.low.lim <- 1 - upp.lim
n.upp.lim <- 1 - low.lim
ci.matrix[n.x+1,]<-c(n.x,n.low.lim,n.upp.lim)
}
}) #CLOSE withProgress
heading <- matrix(NA,ncol=1,nrow=1)
heading[1,1] <-
paste("LCO Confidence Intervals for n = ",n," and Level = ",level,sep="")
rownames(heading) <- c("")
colnames(heading) <- c("")
print(heading,quote=FALSE)
print(ci.matrix)
}
##############################################################################
# The function LCO.CI() generates the LCO confidence intervals #
# for X = 0, 1, ..., n for a specified n and confidence level. #
# #
# Example: To generate all LCO confidence intervals at n=20, #
# level=.90, and 3rd decimal place accuracy, use #
# #
# > LCO.CI(20,.90,3) #
##############################################################################
The MIT License (MIT)
Copyright (c) 2015 Jimmy Doi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# ----------------------------
# App Title: LCO CI Generator
# Author: Jimmy Doi
# ----------------------------
library(shiny)
source("LCO_generator_all_n.r")
shinyServer(function(input, output, session) {
output$textlevel <- renderText({
paste0("Level = ", input$level,"%")
})
output$textsize <- renderText({
paste("Sample size =", input$size)
})
output$textdp <- renderText({
paste(input$dpsize,"decimal place accuracy")
})
output$LCOresults <- renderPrint({
lev <- input$level/100
dp <- switch(input$dpsize,
"2nd" = 2,
"3rd" = 3,
"4th" = 4)
sz <- input$size
LCO.CI(sz,lev,dp)
})
})
# ----------------------------
# App Title: LCO CI Generator
# Author: Jimmy Doi
# ----------------------------
library(shiny)
shinyUI(fluidPage(
tags$head(tags$link(rel = "icon", type = "image/x-icon", href =
"https://webresource.its.calpoly.edu/cpwebtemplate/5.0.1/common/images_html/favicon.ico")),
tags$title("LCO Confidence Interval Generator"),
titlePanel("LCO Confidence Interval Generator"),
div("Note: Please adjust width of browser if only one column is visible.",
style = "font-size: 9pt;color:teal"),br(),br(),
sidebarPanel(
sliderInput("level",
label = h5("Confidence Level %:"),
min = 80, max = 99, value = 95, step=1),br(),
sliderInput("size",
label = h5("Sample Size:"),
min = 1, max = 200, value = 25),br(),
selectInput("dpsize",
label = h5("Decimal Place Accuracy:"),
choices = c("2nd", "3rd", "4th"),
selected = "2nd"),
div("At 4th decimal place accuracy computation time may require up to
25 seconds.", style = "font-size: 9.5pt;color:teal",align="right"),
br(), br(),
div(submitButton("Submit"),align="right"), br(), br(), br(), br(), br(),
div("Shiny app by",
a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
"Jimmy Doi"),align="right", style = "font-size: 8pt"),
div("Base R code by",
a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
"Jimmy Doi"),align="right", style = "font-size: 8pt"),
div("Shiny source files:",
a(href="https://gist.github.com/calpolystat/d896c5848934484181be",
target="_blank","GitHub Gist"),align="right", style = "font-size: 8pt"),
div(a(href="http://www.statistics.calpoly.edu/shiny",target="_blank",
"Cal Poly Statistics Dept Shiny Series"),align="right", style = "font-size: 8pt")
),
mainPanel(
p("Details on the Length/Coverage Optimal (LCO) confidence interval for
the binomial proportion can be found in the following journal
article:"),
# tags$blockquote("Schilling, M., and Doi, J. (2014) 'A Coverage Probability
# Approach to Finding an Optimal Binomial Confidence Procedure'",
# em("The American Statistician"),", 68, 133-145. ",
# a(href="http://amstat.tandfonline.com/doi/abs/10.1080/00031305.2014.899274#.UyNr7oWuomg",
# target="_blank", "(Online access)")),
div("Schilling, M., and Doi, J. (2014) 'A Coverage Probability Approach to Finding an Optimal
Binomial Confidence Procedure'",
em("The American Statistician"),", 68(3), 133--145",
a(href="http://amstat.tandfonline.com/doi/abs/10.1080/00031305.2014.899274#.UyNr7oWuomg",
target="_blank", "(Online access)"),style="padding-left: 20px;
display:block; border-left: 5px solid #faebbc;margin-left:0px"),br(),
p("The ", a(href="http://www.calpoly.edu/~jdoi/LCO/", target="_blank", "LCO website"),
"contains the R code for the CI algorithm and a full listing of LCO CIs
(at 5 decimal places), for", em("n"), " = 1, 2, ..., 100 at the
90, 95, and 99% levels."),
HTML("<hr style='height: 2px; color: #de7008; background-color: #df7109; border: none;'>"),
textOutput("textlevel"),
textOutput("textsize"),
textOutput("textdp"),
br(),
verbatimTextOutput("LCOresults")
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment