% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/misc_helpers.R
\name{applyMovingAverage}
\alias{applyMovingAverage}
\title{applyMovingAverage}
\usage{
applyMovingAverage(
  dt,
  n,
  centered = TRUE,
  x_ = "x",
  y_ = "y",
  by_ = c("id", "sample"),
  maFun = movingAverage
)
}
\arguments{
\item{dt}{a tidy data.table containing two-dimensional data}

\item{n}{the number of samples centered: if FALSE, then average}

\item{centered}{current sample and previous (n-1) samples if TRUE, then
average symmetrically in past and future. (If n is even, use one more
sample from future.)}

\item{x_}{the variable name of the x-values}

\item{y_}{the variable name of the y-values}

\item{by_}{optionally, any variables that provide grouping to the data.
default is none. see details.}

\item{maFun}{a function that accepts x, y, and n as arguments and
returns a list of length 2 with named elements x and y.}
}
\value{
a newly derived data.table where a movingAverage has been applied.
}
\description{
http://www.cookbook-r.com/Manipulating_data/Calculating_a_moving_average/
}
\examples{
data(CTCF_in_10a_profiles_dt)
agg_dt = CTCF_in_10a_profiles_dt[, list(y = mean(y)), by = list(sample, x)]
ggplot(agg_dt) +
    geom_line(aes(x = x, y = y, color = sample))

ma_smooth = applyMovingAverage(agg_dt, n = 5,
    y_ = 'y', by_ = c('sample'))
ggplot(ma_smooth) +
    geom_line(aes(x = x, y = y, color = sample))

ma_smooth$method = "moving_average"
agg_dt$method = "none"
ggplot(rbind(ma_smooth, agg_dt)) +
    geom_line(aes(x = x, y = y, color = method)) +
    facet_wrap(~sample)
}
