title: How to re-sort different column groups to align each other, using a mutual column
body: <p>My data is out of order, meaning that some rows need to be shifted up or down to match a certain order. The correct order is reflected by a column with certain values. Those values correspond to a column that belongs to the disordered group of columns.</p>
  <p>Since there's a mutual column, I'm looking for a way to do this reordering &quot;internally&quot; within the dataframe. Is there an easy way to do it using <code>tidyr</code> or <code>dplyr</code>, in one <code>%&gt;%</code> pipe?</p>
  <h2>Example</h2>
  <p>I asked 3 people to rate how much they like either dogs, cats, or rabbits, on a scale of 1-5. Each person answered the questions in a different order than the other people.</p>
  <pre class="lang-r prettyprint-override"><code>set.seed(2020)
  
  df &lt;- data.frame(respondent_id = c(&quot;ttt&quot;, &quot;ttt&quot;, &quot;ttt&quot;,
                               &quot;xxx&quot;, &quot;xxx&quot;, &quot;xxx&quot;,
                               &quot;zzz&quot;, &quot;zzz&quot;, &quot;zzz&quot;),
             animal = c(&quot;dog&quot;, &quot;cat&quot;, &quot;rabbit&quot;,
                            &quot;dog&quot;, &quot;cat&quot;, &quot;rabbit&quot;,
                            &quot;dog&quot;, &quot;cat&quot;, &quot;rabbit&quot;),
             rating = sample(1:5, size = 9, replace = TRUE),
             order = c(&quot;cat&quot;, &quot;rabbit&quot;, &quot;dog&quot;,
                       &quot;dog&quot;, &quot;rabbit&quot;, &quot;cat&quot;,
                       &quot;rabbit&quot;, &quot;cat&quot;, &quot;dog&quot;))
  
  df
  
  ##   respondent_id animal rating  order
  ## 1           ttt    dog      4    cat
  ## 2           ttt    cat      4 rabbit
  ## 3           ttt rabbit      1    dog
  ## 4           xxx    dog      1    dog
  ## 5           xxx    cat      4 rabbit
  ## 6           xxx rabbit      2    cat
  ## 7           zzz    dog      1  rabbit
  ## 8           zzz    cat      5    cat
  ## 9           zzz rabbit      2    dog
  </code></pre>
  <ul>
  <li>Columns <code>animal</code> and <code>order</code> are the basis for aligning the data.</li>
  <li>When grouping by <code>respondent_id</code>, I'd like to move <code>animal</code> and <code>rating</code> columns (together) up or down so that the value in <code>animal</code> will match the value in <code>order</code>.</li>
  </ul>
  <h2>Desired Output</h2>
  <pre class="lang-r prettyprint-override"><code>  respondent_id animal rating  order
  1           ttt    cat      4    cat
  2           ttt rabbit      1 rabbit
  3           ttt    dog      4    dog
  4           xxx    dog      1    dog
  5           xxx rabbit      2 rabbit
  6           xxx    cat      4    cat
  7           zzz rabbit      2 rabbit
  8           zzz    cat      5    cat
  9           zzz    dog      1    dog
  </code></pre>