我试图了解如何在对过程进行采样后计算经验p值,以测试在“案例”数据集中观察到的变量“ var”是否比“控制”数据集中出现的预期超出预期。已匹配变量“长度”。
cases = data.frame(id = 1:10, length = sample(1:1000,10), var = sample(c(TRUE,FALSE), 10, TRUE))
control = data.frame(id = 1:100, length = sample(1:1000,100), var = sample(c(TRUE,FALSE), 100, TRUE))
res = data.frame()
nperm = 10
for (perm in 1:nperm) {
control_random = control[sample(nrow(control),nrow(control),replace=FALSE),] # draw the control into a random order
for (i in 1:nrow(cases)) { # loop through cases to find a match for each
for (j in 1:nrow(control)) { # for each case, loop through control looking for a match
if (abs(control_random$length[j] - cases$length[i]) < 100) { # match if length is within 100
break
}
}
res = rbind.data.frame(res, data.frame(perm, cases$id[i], control_random$id[j], control_random$var[j] ))
# and remove it so we don't use it again
control_random = control_random[-j,]
}
}
# pvalue:
# count how many times var is TRUE in control set compared to cases
library(dplyr)
num_controls = res %>%
group_by(perm) %>%
summarise(n = sum(control_random.var.j.))
# Is it the number of original true values compared to random controls?
num_cases = sum(cases$var)
pval = (sum(num_controls$n > sum(cases$var))) / nrow(res)
p值正确吗? 如果我们有容器而不是匹配的随机样本,我们将在每个容器中进行比较怎么办? 任何帮助将不胜感激!