如何计算移动平均线

How to calculate a moving average

我今天在 The New York Times 中看到这篇关于冠状病毒的文章,我喜欢这些图表的呈现方式。我知道条形图可以只是在 ggplot 中使用 geom_col() 但我对平滑部分更感兴趣。就像这张图:

他们说 "each red line is the seven-day moving average, which smooths out day-to-day anomalies..." 你是怎么做到的?我有一个数据集,我计划以类似的方式展示它。

谢谢!

遍历数据集:你保留一个包含 7 个数据的数组并计算平均值。然后向前移动一个数据点,将新的数据点推入你的数组,弹出最旧的数据点,然后重新计算。

这采用截至当前点(包括当前点)的 3 个点的 3 个周期移动平均线。前两个点是 NA,因为没有 3 个点,第三个是 (1+2+3)/3=2,第四个是 (2+3+4)/3=3,依此类推。如果您不需要 NA,请省略 fill = NA。如果您想要居中移动平均线,请删除 rollmeanr 末尾的 r。

library(zoo)
x <- 1:10 # test input
rollmeanr(x, 3, fill = NA)
## [1] NA NA  2  3  4  5  6  7  8  9

要取 3 个或更少点的平均值,请使用带有 partial=TRUE 的 rollapplyr。这里输出中的第一个点就是1,因为1的平均值是1。第二个是(1+2)/2=1.5,其余如上。

rollapplyr(x, 3, mean, partial = TRUE)
## [1] 1.0 1.5 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

有关详细信息,请参阅 ?rollapply。

data.table还有一个滚动均值函数,frollmean,可用于此目的:

library(data.table)
library(ggplot2)
library(scales)

# create some data
set.seed(1)
DT <- data.table(N = rescale(dnorm(seq(-10, 10, by=.1)) + 
        runif(201, -.1, .1), c(1, 800)))

# apply rolling mean over 10 data points
DT[, `:=`(rollN = frollmean(N, n = 10, align = "center"), idx = .I)]

ggplot(DT, aes(x=idx, y=N)) + 
    theme_bw() + 
    geom_line() + # original data
    geom_line(data=DT, aes(x=idx, y=rollN), colour = "red", size = 2) +  # rolling mean
    geom_histogram(aes(x=idx, weight = N/10), binwidth = 10, inherit.aes = FALSE, fill="red", alpha = .2) # histogram
#> Warning: Removed 9 row(s) containing missing values (geom_path).

reprex package (v0.3.0)

于 2020 年 3 月 19 日创建