Skip to content

Instantly share code, notes, and snippets.

@joowkim
Created October 12, 2020 20:42
Show Gist options
  • Save joowkim/86db8ae8ad780b0b135b6c850fc6e3ed to your computer and use it in GitHub Desktop.
Save joowkim/86db8ae8ad780b0b135b6c850fc6e3ed to your computer and use it in GitHub Desktop.
one-sample-z.test
z.test <- function(x,n,p=NULL,conf.level=0.95,alternative="less") {
ts.z <- NULL
cint <- NULL
p.val <- NULL
phat <- x/n
qhat <- 1 - phat
# If you have p0 from the population or H0, use it.
# Otherwise, use phat and qhat to find SE.phat:
if(length(p) > 0) {
q <- 1-p
SE.phat <- sqrt((p*q)/n)
ts.z <- (phat - p)/SE.phat
p.val <- pnorm(ts.z)
if(alternative=="two.sided") {
p.val <- p.val * 2
}
if(alternative=="greater") {
p.val <- 1 - p.val
}
} else {
# If all you have is your sample, use phat to find
# SE.phat, and don't run the hypothesis test:
SE.phat <- sqrt((phat*qhat)/n)
}
cint <- phat + c(
-1*((qnorm(((1 - conf.level)/2) + conf.level))*SE.phat),
((qnorm(((1 - conf.level)/2) + conf.level))*SE.phat) )
return(list(estimate=phat,ts.z=ts.z,p.val=p.val,cint=cint))
}
@joowkim
Copy link
Author

joowkim commented Oct 12, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment