Wednesday 11 September 2013

All possible Regression in R: Saving coefficients in a matrix

All possible Regression in R: Saving coefficients in a matrix

I am running code for all possible models of a phylogenetic generalised
linear model. The issue I am having is extracting and saving the beta
coefficients for each model.
I want to save the coefficients into a matrix, where the columns
correspond to a specific variable and the rows correspond to a formula.The
issue arises because the variables are different for every model. So one
cannot simply row bind the coefficients to the matrix.
The example below shows where I am up to in the problem:
y = rnorm(10)
inpdv = matrix(c(rnorm(10), runif(10), rpois(10, 1)), ncol = 3)
colnames(inpdv) = c("A", "B", "C")
data = cbind(y, inpdv)
model.mat = expand.grid(c(TRUE,FALSE), c(TRUE,FALSE), c(TRUE,FALSE))
names(model.mat) = colnames(inpdv)
formula = apply(model.mat, 1, function(x)
paste(colnames(model.mat)[x], collapse=" + "))
formula = paste("y", formula, sep = " ~ ")
formula[8] = paste(formula[8], 1, sep = "")
beta = matrix(NA, nrow = length(formula), ncol = 3)
for(i in 1:length(formula)){
fit = lm(formula(formula), data)
## Here I want to extract the beta coeffecients here into a n * k matrix
## However, I cannot find a way to assign the value to the right cell
in the matrix
}
So I imagine each coefficient will need to be placed into the respective
cell, but I cannot think of a quick and efficient way of doing so.
The true analysis will take place around 30, 000 times, so any tips on
efficiency would also be appreciated.

No comments:

Post a Comment