Skip to content

Instantly share code, notes, and snippets.

@vankesteren
Created March 19, 2019 10:57
Show Gist options
  • Select an option

  • Save vankesteren/e4341bf2445c839a9ca442357d20542c to your computer and use it in GitHub Desktop.

Select an option

Save vankesteren/e4341bf2445c839a9ca442357d20542c to your computer and use it in GitHub Desktop.
Time series convolutions
# convolutions
convolve <- function(x, kernel) {
size <- length(kernel)
x_pad <- c(rep(0, size - 1), x)
out <- rep(0, length(x))
for (i in 1:length(x)) {
out[i] <- x_pad[i:(i + (size - 1))] %*% kernel
}
return(out)
}
p <- 100
x <- numeric(P)
for (i in 2:p) {
x[i] <- x[i-1] + rnorm(1)
}
x <- rnorm(100) + 2
dropkernel <- c(.75, .25)
growkernel <- c(.25, .75)
smoothing <- exp(1:10) / sum(exp(1:10))
smoothing2 <- 20:1 / sum(20:1)
plot(x, type = "b")
lines(convolve(x, smoothing), col = "blue")
lines(convolve(x, smoothing2), col = "orange")
lines(convolve(x, dropkernel), col = "blue")
lines(convolve(x, growkernel), col = "red")
@vankesteren

Copy link
Copy Markdown
Author

Rplot02

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment