Skip to content

Instantly share code, notes, and snippets.

@dholstius
Created June 8, 2012 22:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dholstius/2898533 to your computer and use it in GitHub Desktop.
Save dholstius/2898533 to your computer and use it in GitHub Desktop.
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

@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