Marc Tulla
Marc Tulla

Reputation: 1771

Extractor function for "call" in lm

Is there a generic extractor function for linear models to pull the call from the model? I'm looking to apply a model across a list of dataframes, then extract the call for that model (I'm doing this a bunch of times over many data frames and models, so looking for an easy way to keep track of which model is which)

Example data:

set.seed(1234)
library(plyr)
    data <- data.frame(
        biz = sample(c("telco","shipping","tech"), 50, replace = TRUE),
        region = sample(c("mideast","americas"), 50, replace = TRUE),
        orders = sample(1:50, 50, replace=TRUE),
        revenue = sample(100:150, 50, replace=TRUE)
        )

Now if I wanted to apply a simple lm across this data, by "region" :

modlist <- dlply(data, 'region', function(df){
    summary(lm(revenue ~ orders, data=df))
    })

For something that has a standard extractor function, like "coefficients" = "coef", this is straightforward:

coefs <- ldply(modlist, coef)

But I can't find any way to extract the "call", e.g., "lm(formula = revenue ~ orders, data = df)". Any ideas?

Upvotes: 2

Views: 109

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81753

You can use [[:

lapply(modlist, "[[", "call")
# $americas
# lm(formula = revenue ~ orders, data = df)
# 
# $mideast
# lm(formula = revenue ~ orders, data = df)

Upvotes: 3

MrFlick
MrFlick

Reputation: 206596

Just write your own function to extract the call in the same way stats:::print.lm does

coefs <- ldply(modlist, function(x) deparse(x$call))

Upvotes: 3

Related Questions