Optimizing the function in R by replacing for loop I am trying to create a function that I want to use in my real data. Is there any way to optimize the following function? This is a function I created to filter the data. 

filter &lt;- function(x, m, delt) {
  series &lt;- x
  series_filtered &lt;- rep(0,length(series))
  delta_t &lt;- delt # time step between data points (hours)
  tau_crit &lt;- 3 # critical period (hours)
  theta_crit &lt;-  2*pi*delta_t/tau_crit # critical frequency
  M &lt;- m # number of time steps before and after available in filtering window
  h &lt;- rep(0,(2*M+1)) # initialize the weights
  # get the lanczos coefficients
  for (n in (-1*M):M) { 
    h[M+n+1] &lt;- ifelse(n == 0,theta_crit*delta_t/pi, 
                       (sin(n*theta_crit*delta_t)/(pi*n)) * (sin(n*pi/M)/(n*pi/M)))
  }
  # need to adjust the weights so that they add up to 1
  h_unbiased &lt;-  h/sum(h)
  h &lt;- h_unbiased
  # step through each time for which we'd like to create a filtered value
  for (t in (1+M):(length(series)-M)) {
    for (n in (-1*M):M) {
      # apply the cofficients to create the filtered series
      series_filtered[t] = series_filtered[t] + series[t+n] * h[M+n+1]
    }
  }
  # Filtered data 
  y2 &lt;- series_filtered[(M+1):(length(series)-M)]
  return(y2)
}


Any suggestions on removing for loop and replacing by apply or any other function is appreciated. 

In the above function, I have one single for loop and one double for loop. 

Edit:

A testing can be done by the following data:

x &lt;- 1:100
series &lt;-  sin(2*x)+sin(x/4) + sin(x/8) + rnorm(100)
jd2 &lt;- filter(x=series,m=4, delt=(40/60))
I have tried this, but I don't know, how much (and even if) faster it is. Anyway, you used a lot of redundant code (creating variables M, h_unbiased, delta_t etc.).

filter2 &lt;- function(x, m, delt) {
  series &lt;- x
  tau_crit &lt;- 3 # critical period (hours)
  theta_crit &lt;-  2*pi*delt/tau_crit # critical frequency
  # get the lanczos coefficients
  h &lt;- sapply(-m:m, FUN=function(x)ifelse(x == 0,theta_crit*delta_t/pi, 
    (sin(x*theta_crit*delt)/(pi*x)) * (sin(x*pi/m)/(x*pi/m))))
  # need to adjust the weights so that they add up to 1
  h &lt;- h/sum(h)
  # step through each time for which we'd like to create a filtered value
  y2 &lt;- sapply((1+m):(length(series)-m), function(t){
    sum(unlist(sapply(-m:m, FUN=function(x)(series[t+x]*h[m+x+1]))))
  })
  # return
  return(y2)
}