title: How can I define a constant variable inside a recursive function in R?
body: <p>I want to create functions that compute the Simple Moving Average (SMA) and the Exponential Moving Average (EMA).</p>
  
  <p>My problem is in the EMA implementation. I would like to set a constant variable inside the recursive function that is equal to one of its argument.</p>
  
  <p>Here is my code: </p>
  
  <pre><code>#SMA
  sma &lt;- function(P,t,n)
  {
    return(sum(P[(t-n):(t-1)])/n)
  }
  
  #EMA
  recursive.ema &lt;- function(P,t,n)
  {
    # Here I want to create a constant variable that keeps in memory the first 
    # value of t, i.e. the value of t before the first recursion, so I can use 
    # it as argument of sma function.
    # Something similar to this: tmp &lt;- t (t given from outside the function)
  
    b &lt;- 2/(n+1)
    if (t == 1)
    {
      return(b*P[1] + (1-b)*sma(P,tmp,n))
    }
    return (b*P[t] + (1-b)*recursive.ema(P,t-1,n))
  }
  </code></pre>
  
  <p>Here P is a vector, time series of prices, t is the index of the vector, the time in my model,  and n is any positive number, corresponding to n lagged periods at time t.</p>