【问题标题】:Calculate correlation coefficient by bootstrapping通过自举计算相关系数
【发布时间】:2026-01-11 10:35:01
【问题描述】:

我正在研究 5 种鸟类开始换羽的日期与这 5 种鸟类完成羽毛换羽所需的天数之间的相关性。

我尝试在下面的代码中模拟我的数据。对于 5 个物种中的每一个,我都有 10 个人的开始日和 10 个人的持续时间。对于每个物种,我计算了平均开始天数和平均持续时间,然后计算了这 5 个物种之间的相关性。

我想要做的是引导平均开始日期并引导每个物种的平均持续时间。我想重复这 10,000 次并在每次重复后计算相关系数。然后我想提取 10,000 个相关系数的 0.025、0.5 和 0.975 分位数。

我已经模拟了原始数据,但是一旦我尝试引导,我的代码很快就变得一团糟。谁能帮我解决这个问题?

# speciesXX_start_day is the day of the year that 10 individuals of birds started moulting their feathers
# speciesXX_duration is the number of days that each individuals bird took to complete the moulting of its feathers
species1_start_day <- as.integer(rnorm(10, 10, 2))
species1_duration <- as.integer(rnorm(10, 100, 2))

species2_start_day <- as.integer(rnorm(10, 20, 2))
species2_duration <- as.integer(rnorm(10, 101, 2))

species3_start_day <- as.integer(rnorm(10, 30, 2))
species3_duration <- as.integer(rnorm(10, 102, 2))

species4_start_day <- as.integer(rnorm(10, 40, 2))
species4_duration <- as.integer(rnorm(10, 103, 2))

species5_start_day <- as.integer(rnorm(10, 50, 2))
species5_duration <- as.integer(rnorm(10, 104, 2))

start_dates <- list(species1_start_day, species2_start_day, species3_start_day, species4_start_day, species5_start_day)
start_duration <- list(species1_duration, species2_duration, species3_duration, species4_duration, species5_duration)

library(plyr)

# mean start date for each of the 5 species
starts_mean <- laply(start_dates, mean)

# mean duration for each of the 5 species
durations_mean <- laply(start_duration, mean)

# correlation between start date and duration
cor(starts_mean, durations_mean)

【问题讨论】:

    标签: r twitter-bootstrap simulation correlation normal-distribution


    【解决方案1】:

    R 允许您使用 sample 函数重新采样数据集。为了引导,您可以只取原始数据集的随机样本(带替换),然后重新计算每个子样本的统计数据。您可以将中间结果保存在数据结构中,以便以后处理数据。

    下面添加了针对您的特定问题的可能示例解决方案。我们为每个物种抽取 10000 个大小为 3 的子样本,计算统计数据,然后将结果保存在列表或向量中。引导后我们能够处理所有数据:

    nrSamples = 10000;
    listOfMeanStart = list(nrSamples)
    listOfMeanDuration = list(nrSamples)
    correlations <- vector(mode="numeric", length=nrSamples)
    
    for(i in seq(1,nrSamples))
    {
      sampleStartDate = sapply(start_dates,sample,size=3,replace=TRUE)
      sampleDurations = sapply(start_duration,sample,size=3,replace=TRUE)
    
      listOfMeans[[i]] <- apply(sampleStartDate,2,mean) 
      listOfMeanDuration[[i]] <- apply(sampleDurations,2,mean)
      correlations[i] <- cor(listOfMeans[[i]], listOfMeanDuration[[i]])
    }
    
    quantile(correlations,c(0.025,.5,0.975))
    

    【讨论】:

    • 非常感谢代码,这真的很有用。我想知道如何使用 boot 包做同样的事情?
    • @luciano 我以前从未使用过该软件包,但这里有一个很好的教程/示例:statmethods.net/advstats/bootstrapping.html。您基本上必须定义相关计算函数并通过 boot() 提供数据。从概念上讲,它基本上是相同的过程。
    最近更新 更多