* Encoding: UTF-8. *Fit model. MIXED mathach WITH cses /FIXED=cses /RANDOM=INTERCEPT cses | SUBJECT(school) COVTYPE(UN) /PRINT=SOLUTION TESTCOV G /SAVE=FIXPRED. *sort by Level 2 ID. SORT CASES BY School(A). *set MXLOOP to # Level 2 units. SET MXLOOP = 160. MATRIX. *Input # Level 2 units. COMPUTE N = 160. *Input estimated covariance matrix for Level 2 random effects (Tau, referred to as G by SPSS). COMPUTE Tau = {8.681643, .0507473;.0507473,.6939945}. *Input estimated residual variance at Level 1 (Sigma2). COMPUTE Sigma2 = {36.70020}. *Indicate Level 2 ID variable. GET ID / VARIABLES school. *Indicate dependent variable. GET y / VARIABLES mathach. *Indicate variable name for predicted values based on fixed effects, obtained with FIXPRED option of SAVE subcommand. GET fixpred / VARIABLES FXPRED_1. *assign labels for ID variable and random effects. COMPUTE labels = {"school", "u0", "u1"}. *IF THERE ARE ONLY RANDOM INTERCEPTS (NO RANDOM SLOPES) THEN INCLUDE NEXT COMPUTE LINE; OTHERWISE COMMENT OUT. *inlcude but do not modify next line; constructs constant vector for random intercept. *COMPUTE Z= MAKE(NROW(y),1,1). *IF THERE ARE RANDOM SLOPES THEN INCLUDE NEXT FEW LINES; OTHERWISE COMMENT OUT. *List all predictors with random slopes here in same order these are ordered in random effects covariance matrix. GET Zpred / VARIABLES cses. *inlcude but do not modify next two lines; constructs matrix of predictor values for predictors with random effects, adding constant for intercept. COMPUTE Zconst = MAKE(NROW(y),1,1). COMPUTE Z = {Zconst, Zpred}. *REST OF PROGRAM REQUIRES NO ADDITIONAL USER INPUT. *determine # obs per level 2 unit. COMPUTE NObs = MAKE(N,1,1). COMPUTE rec = 0. LOOP #j = 1 to N. COMPUTE rec = rec + 1. COMPUTE i = 1. LOOP. COMPUTE rec = rec + 1. COMPUTE i = i + 1. COMPUTE NObs(#j) = NObs(#j) + 1. END LOOP IF (id(rec) <> id(rec + 1)). END LOOP. COMPUTE firstobs = 1. COMPUTE u = MAKE(N,NCOL(Z)+1,0). LOOP #j = 1 to N. COMPUTE lastobs = firstobs + nobs(#j) -1. COMPUTE Zj = Z(firstobs:lastobs,:). COMPUTE Rj = Ident(NObs(#j))*Sigma2. COMPUTE Vj = Zj*Tau*T(Zj) + Rj. COMPUTE uj = Tau*T(Zj)*INV(Vj)*(y(firstobs:lastobs) - fixpred(firstobs:lastobs)). COMPUTE u(#j,:) = {ID(firstobs),T(uj)}. COMPUTE firstobs = lastobs + 1. END LOOP. SAVE u / OUTFILE = * / NAMES labels . END MATRIX.