Search code examples
rglm

how to obtain all variable from stepAIC


I would like to keep all the coefficient of stepAIC. Set 0 for the omitted variable and display it same as coef(glm.model)

glm.model=suppressWarnings(glm(as.factor(diagnosis)~.,family = "binomial",data = dat))
step.model=stepAIC(glm.model,trace = FALSE,direction="both")

Originally I have 30 variables, I would like to display all it out from stepAIC and set the value to 0 if it was omitted from stepwise


Solution

  • You can try this below, i use an example dataset from MASS.

    library(MASS)
    example(birthwt)
    glm.model <- glm(low ~ ., family = binomial, data = bwt)
    step.model <- stepAIC(glm.model, trace = FALSE)
    
    # on a vector
    # create an empty vector of zeros
    STEP_COEF = vector("numeric",length(coefficients(glm.model)))
    #same names
    names(STEP_COEF) = names(coefficients(glm.model))
    #fill in the ones found in step
    STEP_COEF[names(coefficients(step.model))] = as.numeric(coefficients(step.model))
    
    > STEP_COEF
    (Intercept)         age         lwt   raceblack   raceother   smokeTRUE 
    -0.12532604  0.00000000 -0.01591847  1.30085571  0.85441418  0.86658183 
        ptdTRUE      htTRUE      uiTRUE        ftv1       ftv2+ 
     1.12885661  1.86689526  0.75064880  0.00000000  0.00000000