[R] regressing each column of a matrix on all other columns

Stefan Mischke mischke at sozpsy.unizh.ch
Thu Jun 16 23:05:56 CEST 2005


DeaR list

I would like to predict the values of each column of a matrix A by 
regressing it on all other columns of the same matrix A. I do this with 
a for loop:

	A <- B <- matrix(round(runif(10*3,1,10),0),10)
	A
	for (i in 1:length(A[1,]))    B[,i] <- as.matrix(predict(lm( A[,i] ~ 
A[,-i] )))
	B

It works fine, but I need it to be faster. I've looked at *apply but 
just can't seem to figure it out.
Maybe the solution could look somewhat like this:

	mylm <- function(y,ci) {
		x <- A[,-ci]
		b <- lm(y~x)
	}	
	B <- apply(A,2,mylm,ci=current_column_index(A))

Is there a way to pass the index of the current column in apply to my 
function? Am I on the right path at all?
Thanks for your help.

Regards, Stefan




More information about the R-help mailing list