Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Last active May 7, 2024 02:06
Show Gist options
  • Save abikoushi/14c904110936d32e523537f2e0cd1059 to your computer and use it in GitHub Desktop.
Save abikoushi/14c904110936d32e523537f2e0cd1059 to your computer and use it in GitHub Desktop.
Shiny application to learn confidence interval (t-dist)
##
p_stat_t <- function(v, df = 1,
alternative = "two.sided"){
if (!alternative %in% c("two.sided", "less", "greater")) {
stop("alternative must be either \"two.sided\", \"less\", or \"greater\".")
}
if(alternative == "two.sided"){
p0 <- 2*pt(abs(v), df, lower.tail = FALSE)
}else if(alternative == "less"){
p0 <- pt(v, df)
}else if(alternative == "greater"){
p0 <- pt(v, df, lower.tail = FALSE)
}
return(p0)
}
q_stat_t <- function(p, df = 1,
alternative = "two.sided"){
if (!alternative %in% c("two.sided", "less", "greater")) {
stop("alternative must be either \"two.sided\", \"less\", or \"greater\".")
}
if(alternative == "two.sided"){
q0 <- qt(p/2, df)#*sign(v)
}else if(alternative == "less"){
q0 <- qt(p, df)
}else if(alternative == "greater"){
q0 <- qt(p, df, lower.tail = FALSE)
}
return(q0)
}
##
require(shiny)
ui <- fluidPage(
# Application title
titlePanel("Learn to confidence interval"),
sidebarLayout(
sidebarPanel(
sliderInput("alpha",
"alpha (false positive rate):",
min = 0.01,
max = 0.5,
value = 0.1)
),
sidebarPanel(
sliderInput("mu0",
"mean of the model of the null hpothesis:",
min = -4,
max = 4,
value = 0,
step=0.1)
)),
mainPanel(plotOutput("distPlot"))
)
server <- function(input, output) {
output$distPlot <- renderPlot({
mu0 <- input$mu0
stat <- 1
invse <- 1
curve(p_stat_t((x-mu0)*invse, df=9), -4, 4,
ylim=c(-0.05, 1.1),
xlab="mean", ylab="alpha", n=501)
arrows(stat-1/invse,0,stat+1/invse,0,
angle=90, code=3, length=0.1, col="grey")
alpha <- input$alpha
q <- q_stat_t(alpha, df=9)
sig <- p_stat_t((stat-mu0)*invse, df=9)<=alpha
points(x=stat, y=0,
pch=ifelse(sig,4,1),
col=ifelse(sig,"firebrick","steelblue"),lwd=2)
abline(h=alpha, lty=2)
abline(v=stat+q, lty=2)
abline(v=stat-q, lty=2)
legend("topright",
legend = c("positive","negative"),
col=c("firebrick","steelblue"),
pch=c(4, 1), lwd=2, lty=0,
box.lwd = 0)
})
}
# 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