drop_levels: Drop unused factor levels to predict from unseen data

drop_levelsR Documentation

Drop unused factor levels to predict from unseen data

Description

Drops unseen factor levels in newdata for which predictions are required from a lm or multinom model fit.

Usage

drop_levels(fit,
            newdata)

Arguments

fit

A fitted lm or multinom model.

newdata

A data.frame containing variables with which to predict.

Value

A data.frame like newdata with unseen factor levels replaced by NA.

Note

This function is so far untested for models other than lm or multinom, though it may still work for other classes.

Author(s)

Keefe Murphy - <keefe.murphy@mu.ie>

See Also

drop_constants

Examples

data(ais)
hema  <- as.matrix(ais[,3:7])
BMI   <- ais$BMI
sport <- ais$sport
sub   <- ais$sport != "Row"

# Fit a linear model
mod   <- lm(hema ~ BMI + sport, data=ais, subset=sub)

# Make predictions
pred1 <- try(predict(mod, newdata=ais), silent=TRUE)
inherits(pred1, "try-error") #TRUE

# Remove unused levels and try again
pred2 <- try(predict(mod, newdata=drop_levels(mod, ais)), silent=TRUE)
inherits(pred2, "try-error") #FALSE
anyNA(pred2)                 #TRUE

MoEClust documentation built on May 29, 2024, 6:44 a.m.