2015-03-02 47 views
1

一些示例數據使用pairwise.t.test,我可以得到P值的矩陣:配對意味着多組?

attach(airquality) 
pairwise.t.test(Ozone, Month) 

這給:

Pairwise comparisons using t tests with pooled SD 

data: Ozone and Month 

    May  Jun  Jul  Aug  
Jun 1.00000 -  -  -  
Jul 0.00026 0.05113 -  -  
Aug 0.00019 0.04987 1.00000 -  
Sep 1.00000 1.00000 0.00488 0.00388 

是否有一個選項(或者不同的功能完全?)做同樣的事情,但每組之間的平均差異?我覺得每一個例子引導我只能從2組獲得的平均差異,相對於超過2

回答

3

您可以用outer功能做到這一點。

# Average monthly ozone 
monthMean = tapply(airquality$Ozone, airquality$Month, mean, na.rm=TRUE) 

# Difference between ozone levels in each pair of months 
outer(monthMean, monthMean, FUN = "-") 

      5   6   7   8   9 
5 0.000000 -5.829060 -35.5000000 -36.3461538 -7.832891 
6 5.829060 0.000000 -29.6709402 -30.5170940 -2.003831 
7 35.500000 29.670940 0.0000000 -0.8461538 27.667109 
8 36.346154 30.517094 0.8461538 0.0000000 28.513263 
9 7.832891 2.003831 -27.6671088 -28.5132626 0.000000 

請注意,矩陣值是行 - 月減列 - 月。如果你想只保留上部或下部三角形,你可以這樣做:

monthDiff = outer(monthMean, monthMean, FUN = "-") 

# Keep upper triangle (set lower triangle to NA) 
monthDiff[lower.tri(month.diff)] = NA 

# Keep lower triangle (set upper triangle to NA) 
monthDiff[upper.tri(month.diff)] = NA 

如果你只是想每月平均值之差的絕對值:

outer(monthMean, monthMean, 
     FUN = function(m1, m2) {abs(m1 - m2)}) 

然後你可以使用upper.trilower.tri擺脫冗餘值。