Learn R Programming

linear.tools (version 1.3.0)

get_x: get x (left hand of var) from model or formula

Description

get x (left hand of var) from model or formula

Usage

get_x(model, method = c("raw", "model", "coeff"), data = NULL)

Arguments

model
a formula or a model.
method
either 'raw','model', or 'coeff', to decide what kind variables to show. Default is 'raw'. See section Detials below.
data
a dataframe, to provide new data to evaluate the model. If NULL (default), then we use the default data in the model.

Value

x variables in the formula or model

Details

What do 'raw' variable, 'model' variable, and 'coeff' variable mean?

  • raw var is the underlying variable without any calculation or transformation.
  • model var is the underlying variable with calculations or transformation.
  • coeff var is the coefficient variable in the model output. So only evaluated model has coeff vars. Most of the time one categorical variable will have several coeff vars according to their contrast encoding. see get_contrast

Example:

In the model, log(price) ~ cut + I(carat^2) in diamonds data, we have:

  • 'raw' variables of x: carat and cut.
  • 'model' variables of x: I(carat^2) and cut.
  • 'coeff' variables of x: cut.L,"cut.Q","cut.C","cut^4" and I(carat^2).

See the sample code below for more examples.

Examples

Run this code

# use the sample code from get_x_hidden
#
data = ggplot2::diamonds
diamond_lm  =  lm(price~  I(carat^   2) + cut  + carat*table ,ggplot2::diamonds)

#_________ input as model
get_x(model = diamond_lm,method = 'raw')
get_x(diamond_lm,method = 'model')
get_x(diamond_lm,method = 'coeff')

#_______ input as formula
get_x(formula(diamond_lm),method = 'model')
# data is required when input is formula
get_x(formula(diamond_lm), data = ggplot2::diamonds, method = 'coeff')

tryCatch(
  get_x(formula(diamond_lm),method = 'coeff'),
  error =function(err){
    print(err)
  }
)



#________ irregular formulas __________

model_dirty = model = lm(price~  I(carat^   2) + cut  - carat:table - cut ,ggplot2::diamonds)

# CORRECT for raw vars
get_x(model_dirty)

# correct for model vars
get_x(price~  I(carat^2) + cut  - carat:table - cut,data = ggplot2::diamonds, method ='model')
get_x(model_dirty,method = 'model')
get_x(model_dirty,data = ggplot2::diamonds, method = 'model')
get_x(model_dirty, method = 'model')

# clean method for model vars
# terms((price~  I(carat^2) + cut  - carat:table - cut)) %>% attr(.,"factors") %>% colnames()
# model_dirty %>% terms %>% attr(.,"factors") %>% colnames()
# formula(model_dirty) %>% terms %>% attr(.,"factors") %>% colnames()

Run the code above in your browser using DataLab