title: How to reorder a character vector of coefficient names by order of appearance in a list of models
body: <p>The <a href="https://CRAN.R-project.org/package=stargazer" rel="nofollow noreferrer">stargazer package</a> in R is fantastic for displaying multiple regression models as side-by-side columns—the standard style for many social science disciplines. However, the package doesn't play well with knitr+pandoc, since it generates output either as HTML or TeX, but not Markdown.</p>
  
  <p>As a solution, I'm creating a function that can generate tables similar to those created with stargazer, but that saves the output as a simple data frame, which I can then render with pacakges like <code>kable</code> and <code>pander</code> in knitted documents. Doing this is trivial with functions like <code>broom::tidy</code>.</p>
  
  <p>I'm stuck, however, on how to order the coefficients displayed in the model. Take these three models, for example. When displayed with stargazer, the final coefficient order is <code>c("wt", "qsec", "hp", "cyl", "gear", "carb", "drat")</code>. The order of all the coefficients is based primarily on the coefficients in the first model (<code>wt</code>, <code>qsec</code>, <code>cyl</code>, <code>gear</code>, <code>carb</code>). When the second model is appended as a new column, the <code>hp</code> row is inserted after <code>qsec</code> and before <code>cyl</code>.</p>
  
  <pre class="lang-r prettyprint-override"><code>lm0 &lt;- lm(hp ~ wt + qsec + cyl + gear + carb, mtcars)
  lm1 &lt;- lm(qsec ~ hp + cyl + gear + carb, mtcars)
  lm2 &lt;- lm(qsec ~ wt + hp + gear + drat, mtcars)
  
  stargazer(lm0, lm1, lm2, type="text")
  </code></pre>
  
  <pre class="lang-none prettyprint-override"><code>====================================================
                (1)           (2)             (3)          
  ----------------------------------------------------
  wt           16.879                       0.827**        
              (12.113)                      (0.383)        
  qsec         -8.124                                      
              (6.109)                                      
  hp                         -0.005        -0.026***       
                            (0.007)         (0.004)        
  cyl         18.210**     -0.811***                       
              (8.785)       (0.280)                        
  gear         13.342      -1.597***         -0.232        
              (15.115)      (0.441)         (0.439)        
  carb         9.277         0.098                         
              (6.345)       (0.222)                        
  drat                                       0.099         
                                            (0.636)        
  Constant     49.424      29.181***       19.530***       
             (171.876)      (2.398)         (2.766)        
  ====================================================
  Note:                    *p&lt;0.1; **p&lt;0.05; ***p&lt;0.01
  </code></pre>
  
  <p>In the end, I hope to generate a character vector of the coefficient names that I can then use with <code>dplyr::arrange()</code> to correctly sort a data frame of multiple model coefficients.</p>
  
  <p>The sorting seems to follow this pseudo algorithm:</p>
  
  <ol>
  <li>Save the first list (<code>list_1</code>) of coefficient names</li>
  <li>Go through the second list of names. If <code>element_1</code> of <code>list_2</code> doesn't match <code>element_1</code> of <code>list_1</code>, check the next element of <code>list_1</code> until there's a match, then insert before the match</li>
  <li>Put <code>element_2</code> of <code>list_2</code> after <code>element_1</code> if it doesn't match anything else in <code>list_1</code></li>
  <li>Repeat with <code>list_3</code>, and so on</li>
  </ol>
  
  <p>Writing simple R code to generate this order, however, has proven more difficult than I thought. Simply concatenating all the coefficient names in a vector and then keeping only unique values doesn't product the correct order, since new variables (like <code>hp</code>) are just added to the end of existing variable names instead of getting inserted in the middle:</p>
  
  <pre class="lang-r prettyprint-override"><code>library(tidyverse)
  names1 &lt;- names(lm0$coefficients) %&gt;% discard(~ .x == "(Intercept)")
  names2 &lt;- names(lm1$coefficients) %&gt;% discard(~ .x == "(Intercept)")
  names3 &lt;- names(lm2$coefficients) %&gt;% discard(~ .x == "(Intercept)")
  
  # New variables just appended
  unique(c(names1, names2, names3))
  
  # [1] "wt"   "qsec" "cyl"  "gear" "carb" "hp"   "drat"
  </code></pre>
  
  <p>Additionally, it seems like the only way to implement something like this is to use a ton of loops, which feels wildly inefficient.</p>
  
  <p>So, in the end, how can I sort or reorder a character vector of coefficient names by order of appearance in a list of models, prioritizing the order of the first model in the list? That is, ultimately this is the character vector I'd like to get: <code>c("wt", "qsec", "hp", "cyl", "gear", "carb", "drat")</code></p>
  
  <hr>
  
  <p>Update: <code>memisc::mtable(lm0, lm1, lm2)</code> is a <a href="https://stackoverflow.com/a/24369399/120898">neat alternative to stargazer</a> that actually returns a data frame (and not just text), but it doesn't insert new coefficients in the already existing order and instead appends them to the list (with <code>hp</code> and <code>drat</code> at the end). It seems to just concatenate all the coefficient names and use their unique values.</p>
  
  <pre class="lang-none prettyprint-override"><code>===================================================
                       lm0        lm1        lm2     
  ---------------------------------------------------
    (Intercept)       49.424   29.181***  19.530***  
                    (171.876)  (2.398)    (2.766)    
    wt                16.879               0.827*    
                     (12.113)             (0.383)    
    qsec              -8.124                         
                      (6.109)                        
    cyl               18.210*  -0.811**              
                      (8.785)  (0.280)               
    gear              13.342   -1.597**   -0.232     
                     (15.115)  (0.441)    (0.439)    
    carb               9.277    0.098                
                      (6.345)  (0.222)               
    hp                         -0.005     -0.026***  
                               (0.007)    (0.004)    
    drat                                   0.099     
                                          (0.636)    
  ---------------------------------------------------
  </code></pre>