applyMovingAverage: applyMovingAverage

View source: R/misc_helpers.R

applyMovingAverageR Documentation

applyMovingAverage

Description

http://www.cookbook-r.com/Manipulating_data/Calculating_a_moving_average/

Usage

applyMovingAverage(
  dt,
  n,
  centered = TRUE,
  x_ = "x",
  y_ = "y",
  by_ = c("id", "sample"),
  maFun = movingAverage
)

Arguments

dt

a tidy data.table containing two-dimensional data

n

the number of samples centered: if FALSE, then average

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.)

x_

the variable name of the x-values

y_

the variable name of the y-values

by_

optionally, any variables that provide grouping to the data. default is none. see details.

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.

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)

jrboyd/seqsetvis documentation built on Dec. 10, 2024, 11:23 a.m.