title: dplyr: using values subset from matrix to create new column with case_when
body: <p>I am trying to use create a new column in a data frame using <code>mutate</code> and <code>case_when</code> but I get unexpected results.</p>
  <p>Here is a dput of a subset of my data: <a href="https://pastebin.com/n37KaMQK" rel="nofollow noreferrer">Pastebin</a>.</p>
  <p>The aim is to calculate own and cross price elasticities for products in multiple completely separate markets. My idea was to use case_when to use different expressions for own and cross elasticities and use a unique product identifier (<code>IDprod_un_j</code> and <code>IDprod_un_l</code>) to subset some values from another matrix. This is the code I am using:</p>
  <pre><code>elast_small %&lt;&gt;% 
    mutate(
      eta_jlm_rc = case_when(
        IDprod_j == IDprod_l ~ (-price_j/share_j) * rowMeans(-alpha_i_rc * share_i_small[IDprod_un_j,] * (1-share_i_small[IDprod_un_j,])),
        IDprod_j != IDprod_l ~ (-price_l/share_j) * rowMeans(alpha_i_rc * share_i_small[IDprod_un_j,] * share_i_small[IDprod_un_l,])
      )
    )
  </code></pre>
  <p>This runs without errors, but when I try to verify the results, I get different values:</p>
  <pre><code>&gt; -elast_small$price_j[1] / elast_small$share_j[1] * mean(-alpha_i_rc * share_i_small[1,] * (1-share_i_small[1,]))
  [1] -10.02669
  &gt; elast_small$eta_jlm_rc[1]
  [1] -14.83231
  </code></pre>
  <p>What am I missing here?</p>