title: By group, match values to a particular value
body: <p>I have a dataset that includes a vote result <code>r</code> for each voter <code>v</code> on a particular decision <code>d</code>. My data thus looks like:</p>
  
  <pre><code>d &lt;- c(1,1,1,1,2,2,2,2,3,3,3,4,4,4,4)
  v &lt;- c(6,7,8,9,6,7,8,9,6,7,9,6,7,8,9)
  r &lt;- c(y,y,n,n,n,n,n,n,y,y,y,y,y,a,y)
  df &lt;- data.frame(d,v,r)
  </code></pre>
  
  <p>Not every voter votes in every election. What I want to do is see if other voters make the same call as a particular voter (let's say <code>v == 8</code>). Normally I would just use <code>dplyr</code>:</p>
  
  <pre><code>df %&gt;% group_by(d) %&gt;% mutate(like8 = ifelse(r == r[v == 8], 1, 0))
  </code></pre>
  
  <p>The problem that I have is that that particular voter <code>v == 8</code> doesn't have a recorded vote for each decision (which is distinct from abstaining votes, which are recorded). Because of this I get the following error.</p>
  
  <blockquote>
    <p>Error in mutate_impl(.data, dots) : 
        Column <code>like8</code> must be length 3 (the group size) or one, not 0</p>
  </blockquote>
  
  <p>What I've done so far is to write up a combination of ifelse and looping in order to get around this issue.</p>
  
  <pre><code>with(df,
      for (i in unique(d)) {
          if(8 %in% v){ 
              for (j in r[d == i]) {
              df$like8[d == i &amp; r == j] &lt;- ifelse(j == r[v == 8], 1, 0)
                                   }
                      } else {
              for (j in r[d == i]){
              df$like8[d == i &amp; r == j] &lt;- NA
                                  } 
                             }
                           }
  )
  </code></pre>
  
  <p>--note: I've never been formally instructed in 'good' programming conventions, so my bracket placement is probably unclear and open to suggestions.</p>
  
  <p>The problem I have is that my actual dataset has over 500,000 observations, and this is extremely slow. I've seen <a href="https://stackoverflow.com/questions/31529630/r-by-group-test-if-for-each-value-of-one-variable-that-value-exists-in-anothe">here</a> solutions using <code>data.table</code> for when the value isn't missing, but I don't understand <code>data.table</code> enough to know how to make it work for my case. </p>