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 <- function(x, m, delt) {
series <- x
series_filtered <- rep(0,length(series))
delta_t <- delt # time step between data points (hours)
tau_crit <- 3 # critical period (hours)
theta_crit <- 2*pi*delta_t/tau_crit # critical frequency
M <- m # number of time steps before and after available in filtering window
h <- rep(0,(2*M+1)) # initialize the weights
# get the lanczos coefficients
for (n in (-1*M):M) {
h[M+n+1] <- 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 <- h/sum(h)
h <- 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 <- 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 <- 1:100
series <- sin(2*x)+sin(x/4) + sin(x/8) + rnorm(100)
jd2 <- filter(x=series,m=4, delt=(40/60))
*apply
are faster thanfor
. In general there's no speed gain, just clarity of code (maybe :-) ). However, anywhere you can vectorize rather than loop you'll save time, and anywhere you can pre-allocate (as you did withseries_filtered
) that'll help too. \$\endgroup\$rcpp
? \$\endgroup\$