lm.Nresponse

A function to fit N linear models for N number of response variables (Yi) against one predictor variable (X) and return the R2- and p-values.

Arguments:

x: either a matrix containing the X variable in the first column and Y variables in the subsequent columns, or a vector of X values (if y is indicated as a separate argument)

y: optional argument to supply a matrix of response variables Yi separately of X

Description: When you've got one predictor variable (X) and multiple response variables (Y1, Y2, ...Yi), and you want to fit a linear model on each (X, Yi) pair, but can't be bothered to manually code multiple lm(Yi~X) models, then this is the function for you.

Example:

X <- seq(0,1,0.01)

Y <- X*2 + rnorm(X, sd=0.1)

Z <- X*2 - rnorm(X, sd=0.1)

M1 <- cbind(X,Y,Z)

M2 <- M1[,-1]

lm.Nresponse(M1)

lm.Nresponse(X, M2)

The function:

lm.Nresponse <- function(x, y=NULL){

if(is.null(y)){X <- x[,1];Y<-x[,-1]}else{

X<-as.numeric(x)

Y<-as.matrix(y)}

modstats <- matrix(ncol=2,nrow=ncol(Y))

for(i in 1:ncol(Y)){

mods <- summary(lm(Y[,i]~X))

r2 <- mods$r.squared

p <- pf(mods$fstatistic[1], mods$fstatistic[2], mods$fstatistic[3], lower.tail = FALSE)

modstats[i,]<-c(r2,p)

}

colnames(modstats)<-c("r.squared","p.value")

rownames(modstats)<-colnames(Y)

return(modstats)

}

##### Function by Manabu Sakamoto, 2012: manabu.sakamoto@gmail.com