如何获得每n个值的移动平均值
How to get moving average of every n values
我有一个这样的数据框
date <- c("2020-09-01","2020-09-01","2020-09-01","2020-09-02","2020-09-02","2020-09-02","2020-09-03","2020-09-03","2020-09-03","2020-09-04","2020-09-04","2020-09-04")
group <- c("red","green","yellow","red","green","yellow","red","green","yellow","red","green","yellow")
number <- c(1,2,3,4,5,6,7,8,9,10,11,12)
df <- data.frame(date, group, number)
我想按 'group' 分组,并有一个名为 'moving average' 的新列,它是第一个和第二个值的平均值,然后是第二个和第三个值的平均值,然后是平均值第 3 和第 4 个值等。然后另一个新列称为 'stdev',它是前 2 个移动平均值的标准差。 (在我的真实示例中,我需要自由地对连续的 30 个值进行平均,而不仅仅是 2 个值)
我希望输出是这样的:
非常感谢您的提前帮助!!
dplyr
方法,假设您的数据已经按日期排列:
df %>%
group_by(group) %>%
mutate(
`moving average` = (number + lag(number)) / 2,
stdev = abs(`moving average` - lag(`moving average`))/sqrt(2)
)
基础 r 方法存在,但涉及更多。
我有一个这样的数据框
date <- c("2020-09-01","2020-09-01","2020-09-01","2020-09-02","2020-09-02","2020-09-02","2020-09-03","2020-09-03","2020-09-03","2020-09-04","2020-09-04","2020-09-04")
group <- c("red","green","yellow","red","green","yellow","red","green","yellow","red","green","yellow")
number <- c(1,2,3,4,5,6,7,8,9,10,11,12)
df <- data.frame(date, group, number)
我想按 'group' 分组,并有一个名为 'moving average' 的新列,它是第一个和第二个值的平均值,然后是第二个和第三个值的平均值,然后是平均值第 3 和第 4 个值等。然后另一个新列称为 'stdev',它是前 2 个移动平均值的标准差。 (在我的真实示例中,我需要自由地对连续的 30 个值进行平均,而不仅仅是 2 个值)
我希望输出是这样的:
非常感谢您的提前帮助!!
dplyr
方法,假设您的数据已经按日期排列:
df %>%
group_by(group) %>%
mutate(
`moving average` = (number + lag(number)) / 2,
stdev = abs(`moving average` - lag(`moving average`))/sqrt(2)
)
基础 r 方法存在,但涉及更多。