Using which to assign Dates
<p>I have a time series of futures contracts values in R called <code>vxdata</code> in long form. At the date where the value moves from numeric to 'NA', I would like to create a column listing that date as the expiration date for that specific contract. I tried the following formula:</p>

<pre><code>vxdata$expiration = vxdata$Dates[which(vxdata$value==NA &amp; lag(vxdata$value)&gt;0]
</code></pre>

<p>I receive the following error:</p>

<blockquote>
  <p>Error in '$&lt;-.data.frame'('<em>tmp</em>', "expiration", value = numeric(0)) :<br>
     replacement has 0 rows, data has 452200</p>
</blockquote>

<p>Any suggestions on a better/correct way to execute this?</p>