Chop It: Look up the Generating Data Frame Columns of a Formula Term

We the moody Gucci, Louis and Pucci men
Escada, Prada
The chopper it got the Uzi lens
Bird’s-eye view
The birds I knew, flip birds
Bird gangs, it was birds I flew

Say you use the base #rstats lm() command

lm(data=dat_foo[,c('y','x1','x2')],y ~ x1 + x2 + x1:x2)

I want to be able to map the single formula term x1:x2 to the two
‘generating’ columns  dat_foo[,c('x1','x2')]

In words, for a term in a ?formula, lookup the involved ‘root’ columns of the data frame inside the formula’s associated environment.

I feel like this mapping must exist under the lm() hood somewhere. Various stackoverflow Q+A’s about formulas never directly talk about this lookup. This Rviews blog post sums up the formula landscape pretty well. But there does not seem to be a convenient expose of the explicit lookup/hash table of the df to term mapping.

I have to hand roll the few lines of code to implement the hash / lookup table myself. My solution is ‘loose’ since it chops up the terms in the formula, then creates many sub-formulas for each chopped term.

Is there a better / preferred way?

One thought on “Chop It: Look up the Generating Data Frame Columns of a Formula Term

  1. After digging deeper, seems like you must still hand-roll a solution. There’s no single function/attribute that does this.

    Found out there’s a weird difference between attributes(terms(formula(mod))) vs attributes(terms(mod))

    attr(terms((mod1)),"dataClasses") # gives something close to initial goal
    attr(terms(formula(mod1)),"dataClasses") # nothing

    Reproducible Example Below as a followup to Ben Bolker’s suggestions

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s