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


Week 2: Random Variables and Central Limit Theorem

Part 1: Motivation - Populations, Samples and Estimates


参考书籍:《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

Mathematical Notation

- Summation

n <- 1000
x <- 1:n
S <- sum(x)

- Greek letters

and it is the \sum notation (capital S in Greek): S = \sum_{i=1}^n x_i

  1. \mu: The unknown average we want to estimate is often denoted with \mu, the Greek letter for m (m is for mean).
  2. \sigma: The standard deviation is often denoted with \sigma, the Greek letter for s.
  3. \varepsilon: Measurement error or other unexplained random variability is typically denoted with \varepsilon, the Greek letter for e.
  4. \beta: Effect sizes, for example the effect of a diet on weight, are typically denoted with \beta.

- Infinity

One way to think about asymptotic results is as results that become better and better as some number increases and we can pick a number so that a computer can’t tell the difference between the approximation and the real number.

onethird <- function(n) sum( 3/10^c(1:n))

1/3 - onethird(4)
# 3.333333e-05
1/3 - onethird(10)
# 3.333334e-11
1/3 - onethird(16)
# 0

In the example above, 16 is practically \infty.

- Integrals

f <- dnorm
x <- seq(-4,4,length=100)
plot(x, f(x), type="l")
x0 <- x[x>2]
y0 <- f(x0)
x0 <- c(min(x0),x0,max(x0))
y0 <- c(0,y0,0)
polygon(x0,y0,col="grey")

\int_2^4 f(x) \, dx

width <- 0.0001
x <- seq(2,4,width)
areaofbars <-  f(x)*width
sum(areaofbars)
# [1] 0.02272117

The smaller we make width, the closer the sum gets to the integral, which is equal to the area.

Random Variables

- sample

population <- read.csv("femaleControlsPopulation.csv")
##use unlist to turn it into a numeric vector
population <- unlist(population) 

control <- sample(population,12)
mean(control)
# [1] 23.47667

control <- sample(population,12)
mean(control)
# [1] 25.12583

control <- sample(population,12)
mean(control)
# [1] 23.72333

Null Distributions

Null hypothesis: the name “null” is used to remind us that we are acting as skeptics: we give credence to the possibility that there is no difference

文献中的数据

control <- filter(dat,Diet=="chow") %>% 
  select(Bodyweight) %>% 
  unlist
treatment <- filter(dat,Diet=="hf") %>% 
  select(Bodyweight) %>% 
  unlist

obsdiff <- mean(treatment) - mean(control)
print(obsdiff)
# [1] 3.020833

建立null distribution: Monte Carlo simulation

n <- 10000
null <- vector('numeric', n)
for (i in 1:n){
  control <- sample(population,12)
  treatment <- sample(population,12)
  null[i] <- mean(treatment) - mean(control)
}

hist(null)
mean(null >= obsdiff)
# 等价于
sum(null >= obsdiff) / n
# [1] 0.0123

mean(abs(null) >= obsdiff)
# [1] 0.0251

p-value: is the probability that an outcome from the null distribution is bigger than what we observed when the null hypothesis is true.

Probability Distributions

载入UsingR包中的数据集

- Cumulative Distribution Function

To define a distribution we compute, for all possible values of a, the proportion of numbers in our list that are below a:
F(a) \equiv \mbox{Pr}(x \leq a)
This is called the cumulative distribution function (CDF).
When the CDF is derived from data, asopposed to theoretically, we also call it the empirical CDF (ECDF).

smallest <- floor(min(x))
largest <- ceiling(max(x))
values <- seq(smallest, largest,len=300)
heightecdf <- ecdf(x)
plot(values, heightecdf(values), type="l",
     xlab="a (Height in inches)",ylab="Pr(x <= a)")

The ecdf function is a function that returns a function.

- Histograms

smallest <- floor(min(x))
largest <- ceiling(max(x))
bins <- seq(smallest, largest)
hist(x,breaks=bins,xlab="Height (in inches)",main="Adult men heights")

- Probability Distribution

if we pick a random height from our list, then the probability of it falling between a and b is denoted with:
\mbox{Pr}(a \leq X \leq b) = F(b) - F(a)

library(rafalib)
n <- 100
nullplot(-5,5,1,30, xlab="Observed differences (grams)", ylab="Frequency")
totals <- vector("numeric",11)
for (i in 1:n) {
  control <- sample(population,12)
  treatment <- sample(population,12)
  nulldiff <- mean(treatment) - mean(control)
  j <- pmax(pmin(round(nulldiff)+6,11),1)
  totals[j] <- totals[j]+1
  text(j-6,totals[j],pch=15,round(nulldiff,1))
  Sys.sleep(1)
}
dir <- system.file(package="dagdata") 
filename <- file.path(dir,"extdata/femaleMiceWeights.csv")
dat <- read.csv(filename)

control <- filter(dat,Diet=="chow") %>% 
  select(Bodyweight) %>% 
  unlist
treatment <- filter(dat,Diet=="hf") %>% 
  select(Bodyweight) %>% 
  unlist

obsdiff <- mean(treatment) - mean(control)


n <- 10000
null <- vector('numeric', n)
for (i in 1:n){
  control <- sample(population,12)
  treatment <- sample(population,12)
  null[i] <- mean(treatment) - mean(control)
}

hist(null)
abline(v=obsdiff, col="red", lwd=2)

Normal Distribution

The probability distribution we see above approximates one that is very common in nature: the bell curve, also known as the normal distribution or Gaussian distribution.

When the histogram of a list of numbers approximates the normal distribution, we can use a convenient mathematical formula to approximate the proportion of values or outcomes in any given interval:

pnorm(obsdiff,mean(null),sd(null))
# [1] 0.9864804
1 - pnorm(obsdiff,mean(null),sd(null))
# [1] 0.01351959

# 根据该数据集形成的正态分布中,超过obsdiff的概率为1.4%

- Standardized units

- Quantile-Quantile (QQ) Plot

edX的视频中提到Q-Q图,补充一下相关知识

  • Exercises
# 构建数据
library(downloader)
url <- "https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extd\
ata/femaleControlsPopulation.csv"
filename <- basename(url)
download(url, destfile=filename)
x <- unlist(read.csv(filename))
> 1
mean(x)
# [1] 23.89338

> 2
avg_total <- mean(x)
set.seed(1)
x_sample <- sample(x,5)
avg_sample <- mean(x_sample)
(avgdiff <- abs(avg_sample - avg_total))
# [1] 0.3293778

> 3
avg_total <- mean(x)
set.seed(5)
x_sample <- sample(x,5)
avg_sample <- mean(x_sample)
(avgdiff <- abs(avg_sample - avg_total))
# [1] 0.3813778

> 4
# C) Because the average of the samples is a random variable.

> 5
set.seed(1)
n <- 1000
null <- vector('numeric',n)
for (i in 1:n){
  samp <- sample(x,5)
  null[i] <- mean(samp)
}

1 - pnorm(mean(x)+1,mean(null),sd(null))
# [1] 0.2363077

hist(null)
abline(v=mean(x)+1, col="red", lwd=2)
> 6
set.seed(1)
n <- 10000
null <- vector('numeric',n)
for (i in 1:n){
  samp <- sample(x,5)
  null[i] <- mean(samp)
}

1 - pnorm(mean(x)+1,mean(null),sd(null))
# [1] 0.2530382

> 7
set.seed(1)
n <- 1000
null <- vector('numeric',n)
for (i in 1:n){
  samp <- sample(x,50)
  null[i] <- mean(samp)
}

1 - pnorm(mean(x)+1,mean(null),sd(null))
# [1] 0.01080894

> 8
set.seed(1)
n <- 1000
null <- vector('numeric',n)
for (i in 1:n){
  samp <- sample(x,5)
  null[i] <- mean(samp)
}

hist(null)

n <- 1000
null <- vector('numeric',n)
for (i in 1:n){
  samp <- sample(x,50)
  null[i] <- mean(samp)
}

hist(null)

# B) They both look roughly normal, but with a sample size of 50 the spread is smaller
> 9
set.seed(1)
n <- 1000
null <- vector('numeric',n)
for (i in 1:n){
  samp <- sample(x,50)
  null[i] <- mean(samp)
}

(results <- pnorm(25,mean(null),sd(null)) - 
    pnorm(23,mean(null),sd(null)))
# [1] 0.9766827

> 10
avg_q <- 23.9
sd_q <- 0.43

(results <- pnorm(25,avg_q,sd_q) - 
    pnorm(23,avg_q,sd_q))
# [1] 0.9765648

Populations, Samples and Estimates

- Population parameters

The mean: \mu_X = \frac{1}{m}\sum_{i=1}^m x_i \mbox{ and } \mu_Y = \frac{1}{n} \sum_{i=1}^n y_i
The variance: \sigma_X^2 = \frac{1}{m}\sum_{i=1}^m (x_i-\mu_X)^2 \mbox{ and } \sigma_Y^2 = \frac{1}{n} \sum_{i=1}^n (y_i-\mu_Y)^2

We refer to such quantities that can be obtained from the population as population parameters.

- Sample estimates

\bar{X}=\frac{1}{M} \sum_{i=1}^M X_i \mbox{ and }\bar{Y}=\frac{1}{N} \sum_{i=1}^N Y_i.

- Exercises

# 构建数据
library(downloader)
url <- "https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extd\
ata/mice_pheno.csv"
filename <- basename(url)
download(url, destfile=filename)
dat <- read.csv(filename)

# 数据预处理
table(is.na(dat$Bodyweight))
# FALSE  TRUE 
#   841     5
dat <- na.omit(dat)
> 1
library(dplyr)
x <- dat %>% 
  filter((Sex == 'M') & (Diet == 'chow')) %>% 
  select(Bodyweight) %>% 
  unlist();x

mean(x)
# [1] 30.96381

> 2
library(rafalib)
?popsd
rafalib::popsd(x)
# [1] 4.420501

popsd : population standard deviation
Returns the population variance. Note that sd returns the unbiased sample estimate of the population varaince. It simply multiplies the result of var by (n-1) / n with n the populaton size and takes the square root.

总结:
popsd返回总体方差后计算,sd返回总体方差的无偏样本估计后计算

> 3
set.seed(1)
X <- sample(x,25)
mean(X)
# [1] 30.5196

> 4 
y <- dat %>% 
  filter((Sex == 'M') & (Diet == 'hf')) %>% 
  select(Bodyweight) %>% 
  unlist();y

mean(y)
# [1] 34.84793

> 5
rafalib::popsd(y)
# [1] 5.574609

> 6
set.seed(1)
Y <- sample(y,25)
mean(Y)
# [1] 35.8036

> 7
(popmdiff <- abs(mean(x) - mean(y)))
# [1] 3.884116
(sampmdiff <- abs(mean(X) - mean(Y)))
# [1] 5.284

> 8
x <- dat %>% 
  filter((Sex == 'F') & (Diet == 'chow')) %>% 
  select(Bodyweight) %>% 
  unlist();x

y <- dat %>% 
  filter((Sex == 'F') & (Diet == 'hf')) %>% 
  select(Bodyweight) %>% 
  unlist();y

set.seed(1)
X <- sample(x,25);X

set.seed(1)
Y <- sample(y,25);Y

(popmdiff <- abs(mean(x) - mean(y)))
# [1] 2.375517
(sampmdiff <- abs(mean(X) - mean(Y)))
# [1] 4.13

> 9
A) The population variance of the females is smaller than that of the males; thus, the sample variable has less variability.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念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

推荐阅读更多精彩内容