Lagged differences
<p>Sample data:</p>

<pre><code>Date &lt;- as.Date(c('1-01-2008','2-01-2008', '3-01-2008','4-01-2008', '5-01-2008', '1-01-2008','2-01-2008', '3-01-2008','4-01-2008', '5-01-2008'), format = "%m-%d-%Y") 
Country &lt;- c('US', 'US','US','US', 'US', 'JP', 'JP', 'JP', 'JP', 'JP') 
Category &lt;- c('Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple') 
Value &lt;- c(runif(10, -0.5, 10))
df &lt;- data.frame(Date, Country, Category, Value)
</code></pre>

<p>I am using the following piece to calculate the lagged growth rate of Value within Country and within Category:</p>

<pre><code>df &lt;- ddply(df, .(Country, Category), transform,
                 Growth6m=c(NA, NA, NA, exp(diff(log(Value), lag = 3))-1))
</code></pre>

<p>Now I am trying to get lagged <em>difference</em> rather than growth rate. This worked fine for the first lag (i.e. subtracting value from the previous row) like this:</p>

<pre><code> df &lt;- ddply(df, .(Country, Category), transform,
          Growth1m=c(NA, diff(Value))) 
</code></pre>

<p>but when I introduce higher order lags (ex. subtracting the first row from the third row), I get the error such as: "arguments imply differing number of rows: 157, 158". I tried playing around with the NA's but to no avail. </p>

<p>Edit: sample data</p>