y=c(4,1,3,5,3,3,1) X=matrix(c( 1,1,0,0,0,1,0,0, 1,1,0,0,0,0,1,0, 1,0,1,0,0,0,1,0, 1,0,1,0,0,0,0,1, 1,0,0,1,0,0,0,1, 1,0,0,0,1,1,0,0, 1,0,0,0,1,0,1,0 ),byrow=T,nrow=7) XX=t(X)%*%X library(MASS) XXgi=ginv(XX) Px=X%*%XXgi%*%t(X) Px round(Px,2) fractions(Px) yhat=Px%*%y yhat bhat=XXgi%*%t(X)%*%y bhat C=matrix(c( 1,1,0,0,0,1,0,0, 1,1,0,0,0,0,1,0, 1,1,0,0,0,0,0,1, 1,0,1,0,0,1,0,0, 1,0,1,0,0,0,1,0, 1,0,1,0,0,0,0,1, 1,0,0,1,0,1,0,0, 1,0,0,1,0,0,1,0, 1,0,0,1,0,0,0,1, 1,0,0,0,1,1,0,0, 1,0,0,0,1,0,1,0, 1,0,0,0,1,0,0,1 ),byrow=T,nrow=12) Cbhat=C%*%bhat Cbhat M=matrix(Cbhat,nrow=4,byrow=T) M apply(M,2,mean) C=matrix(c( 0,0,0,0,0,1,-1,0, 0,0,0,0,0,1,0,-1, 0,0,0,0,0,0,1,-1 ),byrow=T,nrow=3) Cbhat=C%*%bhat Cbhat round(C%*%XXgi%*%t(X),2) customer=factor(c(1,1,2,2,3,4,4)) movie=factor(c(1,2,2,3,3,1,2)) d=data.frame(customer,movie,y) d o=lm(y~customer+movie,data=d) model.matrix(o) coef(o) fitted(o) resid(o) o\$coe o\$fit o\$res -o\$coe[5] -o\$coe[6] o\$coe[5]-o\$coe[6] C=matrix(c( 0,0,0,0,-1,0, 0,0,0,0,0,-1, 0,0,0,0,1,-1 ),byrow=T,nrow=3) C%*%o\$coe C=matrix(c( 1,0,0,0,0,0, 1,0,0,0,1,0, 1,0,0,0,0,1, 1,1,0,0,0,0, 1,1,0,0,1,0, 1,1,0,0,0,1, 1,0,1,0,0,0, 1,0,1,0,1,0, 1,0,1,0,0,1, 1,0,0,1,0,0, 1,0,0,1,1,0, 1,0,0,1,0,1 ),byrow=T,nrow=12) matrix(C%*%o\$coe,nrow=4,byrow=T)