bayesian hw 4

chapter 3

Author

Congyuan He

Published

November 18, 2024

2.4

a

set.seed(2024)
n <- 50
p <- 0.4
sigma2 <- p*(1-p)/n

p1 <- rnorm(10000,p,sqrt(sigma2))

logit_trans <- function(x){log(x/(1-x))}
inverse_logit <- function(x){exp(x)/(1+exp(x))}


logit_p1 <- logit_trans(p1)

logit_p_mean <- logit_trans(p)
logit_p_sd <- sd(logit_p1)

logCI <- c((logit_p_mean+qnorm(0.025)*logit_p_sd),
           logit_p_mean,
           (logit_p_mean+qnorm(0.975)*logit_p_sd)
           )

CI <- inverse_logit(logCI)
CI
[1] 0.2716469 0.4000000 0.5437262

b

set.seed(2024)
n <- 20
p <- 8/20
sigma2 <- p*(1-p)/n

p1 <- rnorm(10000,p,sqrt(sigma2))

logit_trans <- function(x){log(x/(1-x))}
inverse_logit <- function(x){exp(x)/(1+exp(x))}


logit_p1 <- logit_trans(p1)

logit_p_mean <- logit_trans(p)
logit_p_sd <- sd(logit_p1)

logCI <- c((logit_p_mean+qnorm(0.025)*logit_p_sd),
           logit_p_mean,
           (logit_p_mean+qnorm(0.975)*logit_p_sd)
           )

CI <- inverse_logit(logCI)
CI
[1] 0.2013291 0.4000000 0.6380887

2.5

a <- 5;b <- 13;c <- 51;d <- 40
logit_OR <- log(((a+0.5)*(d+0.5))/((b+0.5)*(c+0.5)))
V <- (1/(a+0.5))+(1/(b+0.5))+(1/(c+0.5))+(1/(d+0.5))

logCI <- c((logit_OR+qnorm(0.025)*sqrt(V)),
           logit_p_mean,
           (logit_OR+qnorm(0.975)*sqrt(V))
           )

inverse_logit <- function(x){exp(x)/(1+exp(x))}
CI <- inverse_logit(logCI)
CI
[1] 0.09870119 0.40000000 0.48382989

2.6

odds_ratio <- 0.23
ci_lower <- 0.07
ci_upper <- 0.76
z_value <- 1.96  

log_odds_ratio <- log(odds_ratio)
log_ci_lower <- log(ci_lower)
log_ci_upper <- log(ci_upper)

se_log_odds <- (log_ci_upper - log_odds_ratio) / 2*z_value

ci_log_odds <- c(log_odds_ratio - z_value * se_log_odds, log_odds_ratio + z_value * se_log_odds)
cat("对数优势比的95%置信区间:", ci_log_odds, "\n")
对数优势比的95%置信区间: -3.765491 0.8261393 

2.7

n_HAI <- 51  
n_systemic <- 49 
d_HAI <- 44  
d_systemic <- 46  

# 计算死亡率
p_HAI <- d_HAI / n_HAI
p_systemic <- d_systemic / n_systemic

# 计算对数风险比(log hazard ratio)
log_HR <- log(log(p_HAI) / log(p_systemic))

log_HR 
[1] 0.8487794

3.1

3.2

3.4

3.6

3.7

3.8