I read few answers that deal with stats:filter they've made it only partially clear how convolution works (the part to do with coefficients arrangement), but there are other bits to it.
example:
# convolution with 3 coefficients in filter
filter(1:5,c(f1,f2,f3),method="convolution")
[1] NA 6 9 12 NA
#equivalent to:
NA * f3 + x[1] * f2 + x[2] * f1 #x[0] = doesn't exist/NA
x[1] * f3 + x[2] * f2 + x[3] * f1
x[2] * f3 + x[3] * f2 + x[4] * f1
x[3] * f3 + x[4] * f2 + x[5] * f1
x[4] * f3 + x[5] * f2 + x[6] * f1 #x[6] also doesn't exist
I don't understand where's that X[0] come from; I thought we'd start from x[1]. I suspect this may be to do with the offset mentioned in help document for stats::filter
.
The convolution filter is
y[i] = f[1]*x[i+o] + … + f[p]*x[i+o-(p-1)]
where o is the offset: see sides for how it is determined.
sides: for convolution filters only. If sides = 1 the filter coefficients are for past values only; if sides = 2 they are centred around lag 0. In this case the length of the filter should be odd, but if it is even, more of the filter is forward in time than backward.
I am still as confused as it gets. I don't see how sides explain the offset and not sure that the x[0]
was due to offset.
how does convolution really works in stats::filter?
Probably you should learn on what convolution is. Start from the simplest. ie convolving two signals. I will just describe the details. But you could search the WHY onnline.
So filter(1:5,c(f1,f2,f3),method="convolution")
, uses the default of 2 sides. That is the filter the filter will be centered and if not possible, then the larger end will be into the data. The computation begins where the center of the filter coincides with the first value of the signal. Recall that since the filter is being rolled over the signal, it must be less or equal to the length of the signal. Here is an example.
if the filter is c(1,2,3)
for example then we will center it at 2.
thus to convolve c(1,2,3,4,5)
with c(1,2,3)
, we first reverse
the filter then rollapply
it throughout the signal
:
step 1
1 2 3 4 5
3 2 1
We see that 3 is not multiplied by anything! Thus `3*NA + 2*1+1*2 = NA`
We then move the filter one step and do the math again
1 2 3 4 5
3 2 1
Here all the values are present: 3*1+2*2+1*3 = 10
The third step:
1 2 3 4 5
3 2 1
3*2+2*3+1*4 = 16
We repeat this until the centered value ie 2 coincides with the last value.
If you choose side = 1
then it will not center but rather start by coinciding the last value of the filter with the first value of the signal and finish by coinciding the last value of the filter with the last value of the signal.