drop_constants function

Drop constant variables from a formula

Drop constant variables from a formula

Drops constant variables from the RHS of a formula taking the data set (dat), the formula (formula), and an optional subset vector (sub) as arguments.

drop_constants(dat, formula, sub = NULL)

Arguments

  • dat: A data.frame where rows correspond to observations and columns correspond to variables. Ideally column names should be present.
  • formula: An object of class "formula": a symbolic description of the model to be fitted. Variables in the formula not present in the columns of dat will automatically be discarded. The formula may include interactions, transformations, or higher order terms: the latter must be specified explicitly using the AsIs operator (I).
  • sub: An optional vector specifying a subset of observations to be used in the fitting process.

Returns

The updated formula with constant variables removed.

Note

Formulas with and without intercepts are accommodated.

Examples

data(ais) hema <- as.matrix(ais[,3:7]) sex <- ais$sex BMI <- ais$BMI # Set up a no-intercept regression formula with constant column 'sex' form1 <- as.formula(hema ~ sex + BMI + I(BMI^2) - 1) sub <- ais$sex == "male" # Try fitting a linear model mod1 <- try(lm(form1, data=ais, subset=sub), silent=TRUE) inherits(mod1, "try-error") # TRUE # Remove redundant variables from formula & try again form2 <- drop_constants(ais, form1, sub) mod2 <- try(lm(form2, data=ais, subset=sub), silent=TRUE) inherits(mod2, "try-error") # FALSE

See Also

drop_levels, I

Author(s)

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

  • Maintainer: Keefe Murphy
  • License: GPL (>= 3)
  • Last published: 2025-03-05