title: Pulling data from a different data.frame with dplyr?
body: <p>I have a data frame called dat_new, essentially it is clinic visit data, hrn being a patient ID, and dov being date of visit (multiple visits per person). Then I have a data frame called event with dated hospital admissions (multiple admissions per person). </p>
  
  <p>What I want to do, is for each clinic visit, I want to sum the hospital admissions that occurred prior to that clinic visit, simple.</p>
  
  <p>This works with ddply from plyr, takes a bit of time but works well.</p>
  
  <pre><code>temp &lt;- ddply(dat_new, .(hrn,dov), summarise,
                dka2 = sum(event$event_code[which(event$hrn==hrn &amp; event$doa &lt;= dov)]==2),
                dka3 = sum(event$event_code[which(event$hrn==hrn &amp; event$doa &lt;= dov)]==3),
                dka8 = sum(event$event_code[which(event$hrn==hrn &amp; event$doa &lt;= dov)]==8)
  )
  </code></pre>
  
  <p>Now, trying to rewrite in dplyr, I get an error</p>
  
  <pre><code>Error: binding not found: 'event_code'
  </code></pre>
  
  <p>I have it coded like this:</p>
  
  <pre><code>temp2 &lt;- group_by(dat_new, hrn, dov)
  temp3 &lt;- summarise(temp2,
                     dka2 = sum(event$event_code[which(event$hrn==hrn &amp; event$doa &lt;= dov)]==2))
  </code></pre>
  
  <p>Obviously event_code is not in the temp2 data frame. Is it a case of dplyr can not work with 'other' data frames when 'summarising'? If there is a far better way to be doing the 'lookup'/sum I'm doing I'm all ears. </p>
  
  <p>I did try this a few times trialing loading packages on a vanilla R in different orders to try and eliminate any namespace issues.</p>
  
  <p>Thanks</p>
  
  <p>EDIT - REPRODUCIBLE EXAMPLE</p>
  
  <p>This is a quick and dirty example just to illustrate the issue. If we make a 'lookup' data.frame that has 2 of each car, with a mpg around 500, we can then try and go through the original data.frame, looking up in the new data.frame and summing the two mpgs together. plyr gives the expected, figures around 1000. dplyr errors. </p>
  
  <pre><code># add the model names as a column so they're easier to get at
  mtcars$models &lt;- row.names(mtcars)
  
  # create a 'lookup' table
  xtra &lt;- data.frame(models = rep(row.names(mtcars),2),
                      newmpg = rnorm(2*nrow(mtcars),500,10)
  )
  xtra &lt;- xtra[sample(row.names(xtra)), ]
  
  library(plyr)
  ddply(mtcars, .(models), summarise,
          revisedmpg = sum(xtra$newmpg[models==xtra$models]) )
  # great, one row per car, with both mpgs added together
  library(dplyr)
  
  temp2 &lt;- group_by(mtcars, models)
  temp3 &lt;- summarise(temp2,
                     revisedmpg = xtra$newmpg[models==xtra$models] )
  # error
  </code></pre>