2要因とも対応がない場合(CRFpqデザイン)U [データ数が異なるケース]
ソースコード datはデータ行列,pは要因Aの水準数,qは要因Bの水準数
anova.CRFpq2 <- function(dat,p,q){ num <- p * q ABjk <- c() njk <- c() my.mean <- c() for(i in 1:num){ ABjk[i] <- sum(dat[,i][!is.na(dat[,i])]) njk[i] <- length(dat[,i][!is.na(dat[,i])]) my.mean[i] <- mean(dat[,i][!is.na(dat[,i])]) } ABS <- sum(dat[!is.na(dat)]^2) a <- ABjk b <- njk AB <- sum(ABjk^2 / njk) AB.table <- matrix(my.mean,ncol=q,byrow=TRUE) AB.row.mean <- apply(AB.table,1,mean) AB.col.mean <- apply(AB.table,2,mean) G = sum(AB.table) X = G ^ 2 / (p * q) A = q * sum(AB.row.mean^2) B = p * sum(AB.col.mean^2) AB2 = sum(AB.table^2) nn <- p*q / sum(1/njk) SSa <- nn * (A - X) SSb <- nn * (B - X) SSab <- nn * (AB2 - A - B + X) SSwc <- ABS - AB dfA <- p - 1 dfB <- q - 1 dfAB <- (p - 1) * (q - 1) dfWC <- sum(njk) - p * q MSa <- SSa / dfA MSb <- SSb / dfB MSab <- SSab / dfAB MSwc <- SSwc / dfWC Fa <- MSa / MSwc Fb <- MSb / MSwc Fab <- MSab / MSwc pA <- 1 - pf(Fa,dfA,dfWC) pB <- 1 - pf(Fb,dfB,dfWC) pAB <- 1 - pf(Fab,dfAB,dfWC) result <- matrix(c( SSa, dfA, MSa, Fa, pA, SSb, dfB, MSb, Fb, pB, SSab, dfAB, MSab, Fab, pAB, SSwc, dfWC, MSwc, NA, NA), ncol =5, byrow = TRUE) dimnames(result) <- list(c( "行効果:A", "列効果:B", "交互作用:A*B", "誤差:WC"),c( "SS", "df", "MS", "F-value", "p-value")) result }
〜使用例〜
> dat [,1] [,2] [,3] [,4] [1,] 6 3 5 5 [2,] 6 1 4 2 [3,] 4 2 5 4 [4,] 8 2 4 6 [5,] 7 NA NA 3 [6,] 5 NA NA 4 > anova.CRFpq2(dat,2,2) SS df MS F-value p-value 行効果:A 0.3 1 0.3000 0.2086957 0.653932594 列効果:B 24.3 1 24.3000 16.9043478 0.000816642 交互作用:A*B 14.7 1 14.7000 10.2260870 0.005603254 誤差:WC 23.0 16 1.4375 NA NA