Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apply a rolling mean (or other function) to a ggplot2 layer
require(ggplot2)
require(proto)
StatRollApplyR <- proto(ggplot2:::Stat, {
required_aes <- c("x", "y")
default_geom <- function(.) GeomLine
objname <- "rollapplyr"
calculate_groups <- function(., data, scales, ...) {
.super$calculate_groups(., data, scales, ...)
}
calculate <- function(., data, scales, width, FUN, fill=NA, ...) {
require(zoo)
filtered <- rollapplyr(data$y, width, FUN, fill=fill, ...)
result <- data.frame(x=data$x, y=filtered)
return(result)
}
})
stat_rollapplyr <- StatRollApplyR$new
# Example:
n <- 50
z <- zoo(rnorm(n), seq(as.Date('2012-01-01'), by=1, length.out=n))
p <- qplot(x, y, data=data.frame(x=index(z), y=z))
p <- p + geom_point()
p <- p + stat_rollapplyr(width=7, FUN=mean)
show(p)
@nelsonauner
Copy link

nelsonauner commented May 17, 2016

@holstius I get Error in eval(expr, envir, enclos) : could not find function "eval"

> require(ggplot2)
> require(proto)
> StatRollApplyR <- proto(ggplot2:::Stat, { 
+   required_aes <- c("x", "y")
+   default_geom <- function(.) GeomLine
+   objname <- "rollapplyr"
+   calculate_groups <- function(., data, scales, ...) { 
+     .super$calculate_groups(., data, scales, ...)
+   } 
+   calculate <- function(., data, scales, width, FUN, fill=NA, ...) {
+     require(zoo)
+     filtered <- rollapplyr(data$y, width, FUN, fill=fill, ...)
+     result <- data.frame(x=data$x, y=filtered)
+     return(result)
+   }
+ }) 
Error in eval(expr, envir, enclos) : could not find function "eval"

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