I am seeking some simple (i.e. - no maths notation, long-form reproducible code) examples for the filter
function in R
I think I have my head around the convolu
In the recursive case, I think no need to expand the expression in terms of xi. The key with "recursive" is to express the right hand expression in terms of previous y's.
I prefer thinking in terms of filter size.
filter size =1
y1 <- x1
y2 <- x2 + f1*y1
y3 <- x3 + f1*y2
y4 <- x4 + f1*y3
y5 <- x5 + f1*y4
filter size = 2
y1 <- x1
y2 <- x2 + f1*y1
y3 <- x3 + f1*y2 + f2*y1 # apply the filter for the past value and add current input
y4 <- x4 + f1*y3 + f2*y2
y5 <- x5 + f1*y4 + f2*y3
Here's the example that I've found most helpful in visualizing what recursive filtering is really doing:
(x <- rep(1, 10))
# [1] 1 1 1 1 1 1 1 1 1 1
as.vector(filter(x, c(1), method="recursive")) ## Equivalent to cumsum()
# [1] 1 2 3 4 5 6 7 8 9 10
as.vector(filter(x, c(0,1), method="recursive"))
# [1] 1 1 2 2 3 3 4 4 5 5
as.vector(filter(x, c(0,0,1), method="recursive"))
# [1] 1 1 1 2 2 2 3 3 3 4
as.vector(filter(x, c(0,0,0,1), method="recursive"))
# [1] 1 1 1 1 2 2 2 2 3 3
as.vector(filter(x, c(0,0,0,0,1), method="recursive"))
# [1] 1 1 1 1 1 2 2 2 2 2
With recursive, the sequence of your "filters" is the additive coefficient for the previous sums or output values of the sequence. With filter=c(1,1)
you're saying "take the i-th component in my sequence x and add to it 1 times the result from the previous step and 1 times the results from the step before that one". Here's a couple examples to illustrate
I think the lagged effect notation looks like this:
## only one filter, so autoregressive cumsum only looks "one sequence behind"
> filter(1:5, c(2), method='recursive')
Time Series:
Start = 1
End = 5
Frequency = 1
[1] 1 4 11 26 57
1 = 1
2*1 + 2 = 4
2*(2*1 + 2) + 3 = 11
...
## filter with lag in it, looks two sequences back
> filter(1:5, c(0, 2), method='recursive')
Time Series:
Start = 1
End = 5
Frequency = 1
[1] 1 2 5 8 15
1= 1
0*1 + 2 = 2
2*1 + 0*(0*1 + 2) + 3 = 5
2*(0*1 + 2) + 0 * (2*1 + 0*(0*1 + 2) + 3) + 4 = 8
2*(2*1 + 0*(0*1 + 2) + 3) + 0*(2*(0*1 + 2) + 0 * (2*1 + 0*(0*1 + 2) + 3) + 4) + 5 = 15
Do you see the cumulative pattern there? Put differently.
1 = 1
0*1 + 2 = 2
2*1 + 0*2 + 3 = 5
2*2 + 0*5 + 4 = 8
2*5 + 0*8 + 5 = 15
I spent one hour in reading this, below is my summary, by comparison with Matlab
NOTATION: command in Matlab = command in R
filter([1,1,1], 1, data) = filter(data, [1,1,1], method = "convolution") ; but the difference is that the first 2 elements are NA
filter(1, [1,-1,-1,-1], data) = filter(data, [1,1,1], method = "recursive")
If you know some from DSP, then recursive is for IIR, convolution is for FIR