title: R - nonlinear filter to a time series - filter, lapply or loop?
body: <p>I have a vector containing simple time series data (extracted from a deSolve matrix), which for testing purposes can be:</p>
  
  <pre><code>x &lt;- c(1, 2, 3, 4, 5)
  </code></pre>
  
  <p>and would like to apply the nonlinear filter</p>
  
  <pre><code>x[n]*x[n]-x[n-1]*x[n+1]
  </code></pre>
  
  <p>to all elements of the vector except the first and last elements because the filter can't be applied to these two elements (e.g., when the <code>x[n-1]</code> term meets the first element or the <code>x[n+1]</code> term meets the last element).  Therein lies my problem.</p>
  
  <p>Things I've tried:
  1) The <code>filter()</code> command expects a linear filter (i.e., without multiplication of filter coefficients).
  2) <code>lapply()</code> requires that the function applies to all elements of the list.  </p>
  
  <p>Is a loop the only alternative?</p>
  
  <p>Thanks for your help,
  Carey</p>