## Lect1, 30 Aug 2016 # Decompose a two-way table into an additive pattern plus residual ## Vectors need not look like columns y <- c(5,6,8,4,5.1,7.2) Y <- matrix(y, byrow=T,nrow=2) ## What is the difference? Y1 <- as.vector(Y) Y2 <- t(Y1) Y3 <- t(Y2) # Which are vectors (row or column?), which are matrices? Y; is.matrix(Y); dim(Y) Y1; is.matrix(Y1); dim(Y1) Y2; is.matrix(Y2); dim(Y2) Y3; is.matrix(Y3); dim(Y3) # least squares fit ROW <- factor( c("R1","R1","R1","R2","R2","R2") ) COL <- factor( c("C1","C2","C3","C1","C2","C3") ) mydata <- data.frame(y, ROW,COL) rowm <- matrix(ROW,byrow=T,nrow=2) colm <- matrix(COL,byrow=T,nrow=2) # different ways to think about the ``data'' mydata; Y; rowm; colm # least squares fit syd <- lm(y ~ ROW + COL,data=mydata) # How R sees the exercise: names(syd) syd$model mm <- model.matrix(syd) matrix(mm[,1],byrow=T,nrow=2) matrix(mm[,2],byrow=T,nrow=2) matrix(mm[,3],byrow=T,nrow=2); matrix(mm[,4],byrow=T,nrow=2) thefit <- matrix(syd$fit,byrow=T,nrow=2) # an additive pattern theresid <- round(matrix(syd$resid,byrow=T,nrow=2),3) thefit + theresid # Come back to this stuff later. make.onb <- function(myqr=syd$qr,as.tables=F){ Q <- qr.Q(myqr) if ( !as.tables){ return( Q ) }else{ qr.tables <- list() thedim <- myqr$rank for (j in seq(thedim) ) { qr.tables[[j]] <- matrix(Q[,j],byrow=T,nrow=2) } return(qr.tables) } } # might come in handy: ss <- make.onb() round( t(ss) %*% ss,3) ss <- make.onb(as.tables = T) lapply(ss,round,2)