[R语言] Statistics and R - Week 2-3 《Data Analysis for the Life Sciences》


Week 2: Random Variables and Central Limit Theorem

Part 3: Central Limit Theorem in Practice - The t-distribution in Practice


参考书籍:《Data Analysis for the Life Sciences》

参考视频:

  1. Data Analysis for the Life Sciences Series - rafalib
  2. Professional Certificate in Data Analysis for Life Sciences (Harvard University) - edX

Central Limit Theorem in Practice

Let’s use our data to see how well the central limit theorem approximates sample averages from our data. We will leverage our entire population dataset to compare the results we obtain by actually sampling from the distribution to what the CLT predicts.

dat <- read.csv("mice_pheno.csv") #file was previously downloaded
head(dat)

library(dplyr)
controlPopulation <- filter(dat,Sex == "F" & Diet == "chow") %>%  
  select(Bodyweight) %>% unlist
hfPopulation <- filter(dat,Sex == "F" & Diet == "hf") %>%  
  select(Bodyweight) %>% unlist

Compute the population standard deviations as well. We do not use the R function sd because this would compute the estimates that divide by the sample size - 1 and we want the population estimates.

x <- controlPopulation
N <- length(x)
populationvar <- mean((x-mean(x))^2)

identical(var(x), populationvar)
# [1] FALSE
identical(var(x)*(N-1)/N, populationvar)
# [1] TRUE

So to be mathematically correct, we do not use sd or var. Instead, we use the popvar and popsd function in rafalib

library(rafalib)
sd_hf <- popsd(hfPopulation)
sd_control <- popsd(controlPopulation)

- sapply + replicate取代for loop

Ns <- c(3,12,25,50)
B <- 10000 #number of simulations
res <- sapply(Ns,function(n) {
  replicate(B,mean(sample(hfPopulation,n))-mean(sample(controlPopulation,n)))
})

# 且当前代码需要运行4次
n <- 10000
res <- vector('numeric',n)
for (i in 1:n){
  hf_sam <- sample(hfPopulation,3)
  con_sam <- sample(controlPopulation,3)
  mu_delta <- mean(hf_sam) - mean(con_sam)
  res[i] <- mu_delta
}

- qqplot

# 调整画布分布
mypar(2,2)
# seq(along.with=x) 生成x向量的索引,也可直接写along
for (i in seq(along=Ns)) {
  # signif保留有效数字
  titleavg <- signif(mean(res[,i]),3)
  titlesd <- signif(popsd(res[,i]),3)
  # 字符串格式化
  # paste默认sep=' ', paste0默认sep=''
  title <- paste("N=",Ns[i],"Avg=",titleavg,"SD=",titlesd)
  qqnorm(res[,i],main=title)
  qqline(res[,i],col=2)
}
Ns <- c(3,12,25,50)
B <- 10000 #number of simulations
##function to compute a t-stat
computetstat <- function(n) {
  y <- sample(hfPopulation,n)
  x <- sample(controlPopulation,n)
  (mean(y)-mean(x))/sqrt(var(y)/n+var(x)/n)
}
res <- sapply(Ns,function(n) {
  replicate(B,computetstat(n))
})
mypar(2,2)
for (i in seq(along=Ns)) {
  qqnorm(res[,i],main=Ns[i])
  qqline(res[,i],col=2)
}

This simulation only proves that N=12 is large enough in this case

- Exercises

# 数据获取
library(downloader)
url <- "https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extd\
ata/femaleMiceWeights.csv"
filenames <- "femaleMiceWeights.csv"
if(!file.exists("femaleMiceWeights.csv")) download(url,destfile=filenames)
dat <- read.csv(filenames)

> 1
set.seed(1)
n <- 100
p <- 1/6
zs <- replicate(10000,{
  x <- sample(1:6,n,replace=TRUE)
  (mean(x==6) - p) / sqrt(p*(1-p)/n)
}) 
qqnorm(zs)
abline(0,1)
mean(abs(zs) > 2)
# [1] 0.0431
> 2
mypar(4,2)
origin <- matrix(c(0.5,0.5,0.01,0.01,5,30,30,100),ncol=2)
zs <- matrix('numeric',10000,ncol=4)
for (i in 1:4){
  p <- origin[i,1]
  sides <- 1/p
  n <- origin[i,2]
  zs <- replicate(10000,{
    x <- sample(1:sides,n,replace=TRUE)
    (mean(x==1) - p) / sqrt(p*(1-p)/n)
  }) 
  title <- paste("p=",p,"N=",n)
  hist(zs) # nclass可以指定个数
  qqnorm(zs,main=title)
  abline(0,1)
}
# B) p=0.5 and n=30
> 3
X <- filter(dat, Diet=="chow") %>% 
  select(Bodyweight) %>% 
  unlist

mean(X)
# [1] 23.81333

> 4
# D) X¯ follows a normal distribution with mean µX and standard deviation √σx/12 where σx is the population standard deviation.

> 5
# 0

> 6
X <- filter(dat, Diet=="chow") %>% 
  select(Bodyweight) %>% 
  unlist

sd(X)
# [1] 3.022541

> 7
(1 - pnorm(5.21 / sd(X) * sqrt(12))) * 2
# [1] 2.356222e-09

> 8
sqrt(var(X)/12 + var(Y)/12)
# [1] 1.469867

> 9
(mean(Y) - mean(X)) / sqrt(var(X)/12 + var(Y)/12)
# 等价于
t.test(X,Y)$stat
# [1] 2.055174

> 10
# A) Normal with mean 0 and standard deviation 1

> 11
Z <- (mean(Y) - mean(X)) / sqrt(var(X)/12 + var(Y)/12)
(1 - pnorm(Z)) * 2
# [1] 0.0398622

> 12
t.test(X,Y)$p.value
# [1] 0.05299888

> 13
# B) These are two different assumptions. The t-distribution accounts for the variability introduced by the estimation of the standard error and thus, under the null, large values are more probable under the null distribution

附t.test形成列表的内容:

t-tests in Practice

library(dplyr)
dat <- read.csv("femaleMiceWeights.csv")
control <- filter(dat,Diet=="chow") %>% select(Bodyweight) %>% unlist
treatment <- filter(dat,Diet=="hf") %>% select(Bodyweight) %>% unlist
diff <- mean(treatment) - mean(control)
print(diff)
# [1] 3.020833

We learned that diff, referred to as the observed effect size, is a random variable.
The standard error of this random variable is the population standard deviation divided by the square root of the sample size.

SE(\bar{X}) = \sigma / \sqrt{N}

sd(control)/sqrt(length(control))

Use the sample standard deviation as an estimate of the population standard deviation.

The variance of the difference of two random variables is the sum of its variances

se_diff <- sqrt(
  var(treatment)/length(treatment) +
    var(control)/length(control)
)
# [1] 1.469867

Statistical theory tells us that if we divide a random variable by its SE, we get a new random variable with an SE of 1.

tstat <- diff / se_diff
# [1] 2.055174

# 其实本质就是
(mean(treatment) - mean(control)) / 
  sqrt(var(treatment)/length(treatment) +
    var(control)/length(control)
)

CLT tells us that for large sample sizes, both sample averages mean(treatment) and mean(control) are normal.
Statistical theory tells us that the difference of two normally distributed random variables is again normal, so CLT tells us that tstat is approximately normal with mean 0 (the null hypothesis) and SD 1 (we divided by its SE).

- Q: How often does a normally distributed random variable exceed diff

Either smaller (more negative) than -abs(diff) or larger than abs(diff). We call these two regions “tails” and calculate their size

righttail <- 1 - pnorm(abs(tstat))
lefttail <- pnorm(-abs(tstat))
pval <- lefttail + righttail
print(pval)
# [1] 0.0398622

In this case, the p-value is smaller than 0.05 and using the conventional cutoff of 0.05, we would call the difference statistically significant.

The t-distribution in Practice

If the distribution of the population is normal, then we can work out the exact distribution of the t-statistic without the need for the CLT.

library(rafalib)
mypar(1,2)
qqnorm(treatment)
qqline(treatment,col=2)
qqnorm(control)
qqline(control,col=2)

If we use this approximation, then statistical theory tells us that the distribution of the random variable tstat follows a t-distribution.
The t-distribution has a location parameter like the normal and another parameter called degrees of freedom.

t分布是一簇曲线,其形态变化与n(确切地说与自由度大小有关。自由度df越小,t分布曲线越低平;自由度df越大,t分布曲线越接近标准正态分布(u分布)曲线

CLT approximation considered the denominator of tstat practically fixed (with large samples it practically is), while the t-distribution approximation takes into account that the denominator (the standard error of the difference) is a random variable. The smaller the sample size, the more the denominator varies.

The test based on the CLT approximation is more likely to incorrectly reject the null hypothesis (false positive), while the t-distribution is more likely to incorrectly accept the null hypothesis (false negative).

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容