您可以用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.tri
或lower.tri
擺脫冗餘值。