All possible Regression in R: Saving coefficients in a matrix

前端 未结 2 1557
天涯浪人
天涯浪人 2020-12-20 08:32

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. <

2条回答
  •  爱一瞬间的悲伤
    2020-12-20 09:04

    for(i in 1:length(formula)){
        fit = lm(formula(formula), data)
         beta[i, 1:length(fit$coefficients)] <- fit$coefficients
    }
    

    Update

    Idea: name your columns after coefficients, and assign values to columns by name.

    It is just a dummy example but should help you: Create your output matrix:

    beta <- matrix(NA,  nrow=7, ncol=4)
    colnames(beta) <- c("(Intercept)", 'A', 'B', 'C')
    

    Create some dummy data:

     A <- rnorm(10)
     B <- rpois(10, 1)
     C <- rnorm(10, 2)
     Y <- rnorm(10, -1)
    

    Now you can do something like that:

    fit <- lm(Y ~ A + B + C)
    beta[1, names(fit$coefficients)] <- fit$coefficients
    
    fit <- lm(Y ~ A + B)
    beta[2, names(fit$coefficients)] <- fit$coefficients
    
    fit <- lm(Y ~ A + C)
    beta[3, names(fit$coefficients)] <- fit$coefficients
    
    fit <- lm(Y ~ B + C)
    beta[4, names(fit$coefficients)] <- fit$coefficients
    
    fit <- lm(Y ~ A)
    beta[5, names(fit$coefficients)] <- fit$coefficients
    
    fit <- lm(Y ~ B)
    beta[6, names(fit$coefficients)] <- fit$coefficients
    
    fit <- lm(Y ~ C)
    beta[7, names(fit$coefficients)] <- fit$coefficients
    

提交回复
热议问题