# KeepNotes blog

Stay hungry, Stay Foolish.

0%

• 假设检验的方向
• 一类错误和二类错误
• 效应值大小
• 其他因素

#### 定性检测的样本量估算

``````Z_alpha <- qnorm(p = 0.975, lower.tail = T)
Z_beta <- qnorm(p = 0.8, lower.tail = T)
P0 <- 0.9
Pt <- 0.95
n <- (Z_alpha * sqrt(P0 * (1 - P0)) + Z_beta * sqrt(Pt * (1 - Pt)))^2 / (Pt - P0)^2
> n
[1] 238.0332``````

``````> qnorm(0.975)^2 * 0.85 * (1 - 0.85) / 0.05^2
[1] 195.9144``````

``````sampleSize <- function(n, z, p, limit){
t1 <- 1/2 * (2 * n * p + z^2) / (n + z^2)
t2 <- 1/2 * z * sqrt(z^2 + 4 * n * p * (1 - p)) / (n + z^2)
return(t1 - t2 - limit)
}

z <- qnorm(0.975)
p <- 0.77
limit <- 0.7
N <- uniroot(sampleSize, c(1, 1000), tol = 1e-08, z = z, p = p, limit = limit)
str(N)
# pracma::regulaFalsi(sampleSize, 1, 1000, z = z, p = p, limit = limit)``````

#### 定量检测的样本量估算

``````CIxcorr <- function(alpha, corr, N) {
# Computes a confidence interval for a Pearson correlation
# Args:
# alpha: alpha level for (1-alpha) confidence
# corr: value of correlation
# N: sample size
# Returns:
# confidence interval
Z <- qnorm(1 - alpha/2)
# Z = 1.9599640 for 95% CI
se <- sqrt(1/((N - 3)))
zr <- log((1 + corr)/(1 - corr))/2
LL0 <- zr - Z*se
UL0 <- zr + Z*se
LL <- (exp(2*LL0) - 1)/(exp(2*LL0) + 1)
UL <- (exp(2*UL0) - 1)/(exp(2*UL0) + 1)
CI2w <- UL - LL
# CI width CI2w output added to Bonett’s CIcorr R-function
CI <- c(LL, UL, CI2w)
return(CI)
}
CIxcorr(0.05, 0.986, 45)

sizeCIcorr <- function(alpha, corr, CI2w) {
# Computes sample size required to estimate a correlation with desired precision
# Args:
# alpha: alpha level for 1-alpha confidence
# corr: planning value of correlation
# CI2w: desired confidence interval width
# Returns:
# required sample size
z <- qnorm(1 - alpha/2)
n1 <- ceiling(4*(1 - corr^2)^2*(z/CI2w)^2 + 3)
zr <- log((1 + corr)/(1 - corr))/2
se <- sqrt(1/(n1 - 3))
LL0 <- zr - z*se
UL0 <- zr + z*se
LL <- (exp(2*LL0) - 1)/(exp(2*LL0) + 1)
UL <- (exp(2*UL0) - 1)/(exp(2*UL0) + 1)
N <- ceiling((n1 - 3)*((UL - LL)/CI2w)^2 + 3)
return(N)
}
sizeCIcorr(0.05, 0.986, 0.018)``````