title: Is there an R function to aggregate coefficients of interaction effects of a linear model?
body: <p>I am looking for an automated way to perform linear regression with control for an effect of a variable.
  Therefore, I want to:</p>
  <ol>
  <li>Make a linear model with interaction terms with some factor A.</li>
  <li>Assign frequencies of a given factor A to the interaction terms.</li>
  <li>Aggregate coefficients so that the output does not contain the factor. So the final coefficients are  calculated as the weighted average over the factor's frequencies.</li>
  </ol>
  <p>Below there is an example of what I want to achieve.</p>
  <pre><code>#dataset used
  mtcars
  
  #base model with drat and wt as predictors
  model_simple &lt;- lm(mpg~ drat + wt, data = mtcars)
  coefs_simple &lt;- model_simple$coefficients
  
  #model with interaction terms, controlling for the effect of vs
  mtcars$vs &lt;- as.factor(mtcars$vs)
  model_int &lt;- lm(mpg~ vs*drat + vs*wt, data = mtcars)
  
  coefs_int &lt;- model_int$coefficients
  coefs_int
  
  #frequencies of 'vs' levels
  vs_tab &lt;- table(mtcars$vs)
  vs_tab
  
  #coefficients of the second model
  drat_coef &lt;- (vs_tab['0']/sum(vs_tab))*coefs_int['drat'] + (vs_tab['1']/sum(vs_tab))*(coefs_int['drat'] + coefs_int['vs1:drat'])
  drat_coef
  wt_coef &lt;- (vs_tab['0']/sum(vs_tab))*coefs_int['wt'] + (vs_tab['1']/sum(vs_tab))*(coefs_int['wt'] + coefs_int['vs1:wt'])
  wt_coef
  
  coefs_controlled = c(coefs_int['(Intercept)'], 'drat' = as.numeric(drat_coef), wt_coef)
  
  comparison &lt;- data.frame(simple_model_coefs = coefs_simple,
                           coefs_controlled = coefs_controlled)
  
  comparison
  </code></pre>
  <p>The dataset and the model in the snippet are meaningless, I am asking for the programming tool to automate the process. If it's not in base R, maybe there is some tidymodels solution?</p>