如何计算移动平均值

问题描述 投票:0回答:3

我今天在The New York Times中遇到了有关冠状病毒的文章,我喜欢这些图的显示方式。我知道条形图只能在ggplot中使用geom_col(),但我对平滑部分更感兴趣。就像这张图:

enter image description here

他们说:“每条红线是7天移动平均线,可以消除日常异常...”,您该怎么做?我有一个计划以类似方式呈现的数据集。

谢谢!

r ggplot2 moving-average
3个回答
0
投票

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


0
投票

这将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点或更少的平均值,请使用带有部分= 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了解更多信息。


0
投票

[data.table也具有滚动均值功能,rfrollmean,可用于此目的:

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-03-19创建

© www.soinside.com 2019 - 2024. All rights reserved.