title: R diff() and 0 values
body: <p>I want to use <code>diff(log(myvar))</code> to calculate some time-series log returns. Some of the values in <code>myvar</code> are set to <code>0</code> and <code>diff()</code> returns <code>Inf</code> in this case, as it should mathematically.</p>
  
  <p>How can I force <code>diff()</code> to make an exception and return <code>0</code> when either data point of the lagged pair is <code>0</code>? For example</p>
  
  <pre><code>diff(log(c(0,1,2,3,4)))
  </code></pre>
  
  <p>Would return</p>
  
  <pre><code>0 0.6931472 0.4054651 0.2876821
  </code></pre>
  
  <p>Forcing the very first calculated value to be <code>0</code> rather than <code>Inf</code>.</p>
  
  <p><strong>UPDATE</strong>
  I actually had a problem using is.infinite(). Consider the following case:</p>
  
  <pre><code>&gt; v = diff(log(c(1, 0, 0, 2, 3)))
  &gt; v 
  [1]      -Inf       NaN       Inf 0.4054651
  &gt; is.infinite(v) 
  [1]  TRUE FALSE  TRUE FALSE
  </code></pre>
  
  <p>Here we have 3 different cases, -Inf, Inf and NaN. The goal is set 0 to all returns whose base quotation is 0 so I had to add <code>v[is.nan(v)] = 0</code>.</p>
  
  <p>Why would I want to set returns to 0 rather than NA? Well this is more of a logical problem rather than a programming question, but the idea is that in my case 0 means that the reference price hasn't changed (and not that it is unknown).</p>