lm_sweep = function(C, pi){ # # Performs the sweep operator: # # *) http://node101.psych.cornell.edu/Darlington/sweep.htm # *) Page 687 of the Hocking book # # on an input matrix C # m = dim(C)[1] n = dim(C)[2] PV = 1./C[pi,pi] row_pi = t( as.matrix( C[pi, ] ) ) col_pi = as.matrix( C[, pi] ) G = C - ( col_pi %*% row_pi ) * PV # step 2 G[pi, ] = C[pi, ] * PV # step 3 G[, pi] = -C[, pi] * PV # step 4 G[pi, pi] = PV G } verifty_lm_sweep = function(){ # # Verify the above implementation of the lm_sweep function: # lines = '9 3 4 -2 5 3 8 6 5 4 4 6 7 3 1 -2 5 3 9 2 5 4 1 2 8' con = textConnection( lines ) T = read.table( con, header=FALSE ) close(con) colnames(T) = 1:dim(T)[1] T = as.matrix( T ) T1 = lm_sweep(T, 1) T2 = lm_sweep(T1, 2) T3 = lm_sweep(T2, 3) # <- this matches the matrix found on the Darlington sweep web page mentioned above T3 }