jthaman / ciTools

An R Package for Quick Uncertainty Intervals
GNU General Public License v3.0
106 stars 9 forks source link

`add_ci.lmerMod` error when lmer given rank-deficient model #36

Closed matthewravery closed 6 years ago

matthewravery commented 6 years ago

When lmer is given a rank-deficient model matrix, it may go ahead and fit the model anyways, dropping columns as necessary. It produces a message when it does this if you look at the model object, fit or summary(fit). You can also look at the messages via summary(fit)$fitMsgs.

When this takes place, add_ci.lmerMod produces an error:

Error in X %*% vcovBetaHat : non-conformable arguments

I have a fix for this in the latest push of my master fork if you want to grab it. Alternatively, over-write get_x_matrix_mermod from helper_functions.R with the following:

get_x_matrix_mermod <- function(tb, fit){

    ##This function is necessary to avoid cases where the new data upon
    ##which CIs are generated does not contain all levels for one or more
    ##factors from the original data set. New and old data sets are
    ##appended, the model matrix is generated, and the function returns
    ##only the rows corresponding to the new data.
    mm <- fit@frame
    rv <- names(mm)[1]
    mm[[rv]] <- as.numeric(mm[[rv]])

    for(i in names(mm)){
        if(is.factor(mm[[i]])) mm[[i]] <- as.character(mm[[i]])
    }

    X <- suppressWarnings(model.matrix(reformulate(attributes(terms(fit))$term.labels), 
                                       dplyr::bind_rows(mm, tb))[-(1:nrow(fit@frame)), ])

    #remove columns from X that weren't used in the model fit
    X[, colnames(X)[colnames(X) %in% colnames(model.matrix(fit))]]
}
jthaman commented 6 years ago

Closed by #38