r - R 上相关系数的自举 p 值
问题描述
在 上R
,我使用 boostrap 方法来获得相关系数估计和置信区间。为了得到 p 值,我想,我可以计算不包含零的置信区间的比例。但这不是解决方案。
在这种情况下如何获得 p 值?
我cor.test
用来获取系数估计。cor.test
还可以给我每次测试的 p 值。但是我怎样才能得到引导的 p 值呢?
非常感谢 !
下面是一个例子:
n=30
data = matrix (data = c (rnorm (n), rnorm (n),rnorm (n), rpois(n,1),
rbinom(n,1,0.6)), nrow = n, byrow = F)
data= as.data.frame(data)
z1 = replicate( Brep, sample(1:dim(data)[1], dim(data)[1], replace = T))
res = do.call ( rbind, apply(z1, 2, function(x){ res=cor.test(data$V1[x], data$V2[x]) ; return ((list(res$p.value,res$estimate))) }))
coeffcorr = mean(unlist(res[,2]), na.rm = T) #bootstrapped coefficient
confInter1 = quantile(unlist(res[,2]), c(0.025, 0.975), na.rm = T)[1] #confidence interval 1
confInter2 = quantile(unlist(res[,2]), c(0.025, 0.975), na.rm = T)[2] #confidence interval 2
p.value = mean (unlist(res[,1]), na.rm = T ) # pvalue
解决方案
R 中引导的标准方法是使用 base package boot
。首先定义 bootstrap 函数,该函数接受两个参数,即数据集和数据集的索引。这是bootCorTest
下面的功能。在函数中,您对数据集进行子集化,仅选择索引定义的行。
其余的很简单。
library(boot)
bootCorTest <- function(data, i){
d <- data[i, ]
cor.test(d$x, d$y)$p.value
}
# First dataset in help("cor.test")
x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)
y <- c( 2.6, 3.1, 2.5, 5.0, 3.6, 4.0, 5.2, 2.8, 3.8)
dat <- data.frame(x, y)
b <- boot(dat, bootCorTest, R = 1000)
b$t0
#[1] 0.10817
mean(b$t)
#[1] 0.134634
boot.ci(b)
有关函数结果的更多信息boot
,boot.ci
请参阅它们各自的帮助页面。
编辑。
如果要从引导统计函数返回多个值bootCorTest
,则应返回一个向量。在以下情况下,它返回一个具有所需值的命名向量。
请注意,我设置了 RNG 种子,以使结果可重现。我应该已经在上面做了。
set.seed(7612) # Make the results reproducible
bootCorTest2 <- function(data, i){
d <- data[i, ]
res <- cor.test(d$x, d$y)
c(stat = res$statistic, p.value = res$p.value)
}
b2 <- boot(dat, bootCorTest, R = 1000)
b2$t0
# stat.t p.value
#1.841083 0.108173
colMeans(b2$t)
#[1] 2.869479 0.133857
推荐阅读
- dask - 如何在 dask 分布式集群中使用 dask_ml 预处理
- docker - 如何在没有 URL 的情况下使用 HELM 提取图像
- css - 为什么某些 Tailwind 类在 JetStream 中不起作用?
- qt - 如何将数据写入多个 QFile
- scipy - python - 如何在python中给定ND中的网格得到k阶有限元基(样条基)?
- python - Python保存循环Seaborn图
- python - 给定索引列表,从列表中删除多个条目
- javascript - 在 Grafana 中选择新区域时从图形面板获取新时间范围?
- typescript - 如何在 TypeScript 中将自定义界面与导入的界面合并?
- openstreetmap - 打开街道地图点击添加坐标到文本框