Home > Blockchain >  Extract restricted regression coefficients without using tidy
Extract restricted regression coefficients without using tidy

Time:02-20

I'm using the restriktor package to perform restricted regressions; however, at the same time I'm doing the restricted regressions by group using the dplyr. In order to extract the coefficients and have them formatted into a nice panel format, I use tidy and broom but the tidy packaged doesn't work on the restriktor so I'm not sure how to go about extracting the coefficients:

library(restriktor)
library(dplyr)
reg = 
  mtcars %>%
  group_by(cyl) %>%
  do(model = restriktor(lm(mpg ~ wt   hp, data =.), constraints = ' wt  < -4 '))

I would like to have the b.restr which is the restricted model coefficients to be extracted for each group and formatted together into a panel normally I would use the following:

reg = 
  mtcars %>%
  group_by(cyl) %>%
  do({model = restriktor(lm(mpg ~ wt   hp, data =.), constraints = ' wt  < -4 ')    # create your model
  data.frame(tidy(model),              # get coefficient info
             glance(model))})

But I get the following error:

Error: No tidy method for objects of class restriktor

All I want is to extract the following elements from the lists and put them altogether with their group identifier in one panel format:

reg[[2]][[1]][["b.restr"]]

CodePudding user response:

Use group_modify (which is preferred over do now) with coef/as.list/as_tibble.

library(dplyr)
library(restriktor)

# coefficients or NAs if too few rows for restriktor
co <- function(fo, data) {
   fm <- lm(fo, data)
   coef_lm <- coef(fm)
   min_rows <- length(coef_lm)
   if (nrow(data) <= min_rows) NA * coef_lm
   else coef(restriktor(fm, constraints = ' wt  < -4 '))
}

mtcars %>%
  group_by(cyl) %>%
  group_modify(~ {
    .x %>%
      co(mpg ~ wt   hp, .) %>%
      as.list %>%
      as_tibble
  }) %>%
  ungroup

giving:

# A tibble: 3 x 4
    cyl `(Intercept)`    wt      hp
  <dbl>         <dbl> <dbl>   <dbl>
1     4          45.8 -5.12 -0.0905
2     6          35.3 -4    -0.0256
3     8          33.9 -4    -0.0132
  • Related