0

我正在研究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) 

回答

2

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)) 
+0

非常感謝代碼,這真的很有用。我想知道如何用'boot'包做同樣的事情? – luciano

+0

@luciano我從來沒有使用過這個包,但這裏有一個很好的教程/示例:http://www.statmethods.net/advstats/bootstrapping.html。你基本上必須定義你的相關性計算函數,並通過boot()提供你的數據。從概念上講,這基本上是一樣的過程。 –