簡體   English   中英

R 如何根據比例計算置信區間

[英]R how to calculate confidence interval based on proportion

我是 R 的新手並試圖學習統計數據。這是我試圖弄清楚的一個練習問題點我 我應該如何使用 R 代碼根據這個數學方程創建 function?

我有一個像這樣的 dataframe 點我 df中的“暴露”列包含兩組,一組稱為“測試組(暴露)”,另一組稱為“控制組”。 所以數學 function 指的是這兩組。

在另一種實踐中,我在這里有這些代碼來計算置信區間

# sample size
# OK for non normal data if n > 30
n <- 150

# calculate the mean & standard deviation
will_mean <- mean(will_sample)
will_s <- sd(will_sample)

# normal quantile function, assuming mean has a normal distribution:
qnorm(p=0.975, mean=0, sd=1) # 97.5th percentile for a N(0,1) distribution
# a.k.a. Z = 1.96 from the standard normal distribution

# calculate standard error of the mean
# standard error of the mean = mean +/- critical value x (s/sqrt(n))
# "q" functions in r give the value of the statistic at a given quantile
critical_value <- qt(p=0.975, df=n-1)
error <- critical_value * will_s/sqrt(n)

# confidence inverval 
will_mean - error
will_mean + error

但我不確定如何處理暴露的 2 組

如果您有至少一種編程語言的經驗,請不要擔心這很容易,R 非常簡單。 R 和大多數其他編程語言之間唯一顯着的區別是 R 是為統計目的而開發的。 您可以使用 function qnorm() 默認情況下,它設置為標准化正態分布,就像您的情況一樣,但您可以使用文檔獲取更多詳細信息,可通過命令?qnorm()訪問。 實際上在練習中你不需要計算它,因為你必須將它作為參數傳遞,但實際上你需要。 代碼應該是這樣的:

conf <- function(p1,p2,n1,n2,z){
      part = z*(p1*(1-p1)/n1+p2*(1-p2)/n2)**(1/2)
      return(c(p1-p2-part,
               p1-p2+part))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM