Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Last active May 5, 2024 07:23
Show Gist options
  • Save abikoushi/34b6cd02afd15684218748416552c399 to your computer and use it in GitHub Desktop.
Save abikoushi/34b6cd02afd15684218748416552c399 to your computer and use it in GitHub Desktop.
Shiny application to learn p-value
##
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 p-value"),
sidebarLayout(
sidebarPanel(
sliderInput("alpha",
"alpha (false positive rate):",
min = 0.01,
max = 0.5,
value = 0.1)
),
mainPanel(plotOutput("distPlot"))
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
stat <- 1.2
curve(p_stat_t(x, df=9), -4, 4,
xlab="t-stat",ylab="alpha")
legend("topright",
legend = c("positive","negative"),
col=c("firebrick","steelblue"),
pch=c(4,1), lwd=2, lty=0,
box.lwd = 0)
alpha <- input$alpha
q <- q_stat_t(alpha, df=9)
sig <- p_stat_t(stat, 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=q,lty=2)
abline(v=-q,lty=2)
})
}
# 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