英文:
How to calculate moving average from bottom to up
问题
有一个名为df
的数据框,如何添加moving_average
变量作为图像?我想要从底部向上计算,只计算两个日期。
library(tidyverse)
df <- data.frame(value=c(1:10))
英文:
There is dataframe df
, how to add moving_average
variable as image ? I want to the calculate bottom up and just calculate two dataes.
library(tidyverse)
df <- data.frame(value=c(1:10))
答案1
得分: 2
这是一个使用zoo
包的解决方案。
df <- data.frame(value=0:10)
df$moving_average <- zoo::rollmeanr(df$value, k = 2L, fill = NA)
is.na(df$moving_average) <- (seq_along(df$value) - 1L) %% 2L == 1L
df
#> value moving_average
#> 1 0 NA
#> 2 1 NA
#> 3 2 1.5
#> 4 3 NA
#> 5 4 3.5
#> 6 5 NA
#> 7 6 5.5
#> 8 7 NA
#> 9 8 7.5
#> 10 9 NA
#> 11 10 9.5
创建于2023-08-10,使用 reprex v2.0.2
英文:
Here is a solution with package zoo
.
df <- data.frame(value=0:10)
df$moving_average <- zoo::rollmeanr(df$value, k = 2L, fill = NA)
is.na(df$moving_average) <- (seq_along(df$value) - 1L) %% 2L == 1L
df
#> value moving_average
#> 1 0 NA
#> 2 1 NA
#> 3 2 1.5
#> 4 3 NA
#> 5 4 3.5
#> 6 5 NA
#> 7 6 5.5
#> 8 7 NA
#> 9 8 7.5
#> 10 9 NA
#> 11 10 9.5
<sup>Created on 2023-08-10 with reprex v2.0.2</sup>
答案2
得分: 1
尝试以下类似的ave
函数用法:
transform(
df,
moving_average = ave(value,
rev((seq_along(value)-1) %/% 2),
FUN = \(x) c(NA, mean(x))[seq_along(x)]
)
)
这会得到以下结果:
value moving_average
1 1 NA
2 2 1.5
3 3 NA
4 4 3.5
5 5 NA
6 6 5.5
7 7 NA
8 8 7.5
9 9 NA
10 10 9.5
英文:
Try ave
like below
transform(
df,
moving_average = ave(value,
rev((seq_along(value)-1) %/% 2),
FUN = \(x) c(NA, mean(x))[seq_along(x)]
)
)
which gives
value moving_average
1 1 NA
2 2 1.5
3 3 NA
4 4 3.5
5 5 NA
6 6 5.5
7 7 NA
8 8 7.5
9 9 NA
10 10 9.5
答案3
得分: 1
使用rollapply
函数,参数为by = 2
和align = "left"
,然后再将结果反转,或者使用ave
函数,将gl
反转。
library(zoo)
df <- data.frame(value=0:10)
transform(df, ma = rev(rollapply(rev(value), 2, mean, by = 2, fill = NA, align = "left")))
# 或者
n <- nrow(df)
transform(df, ma = ave(value, rev(gl(n, 2, n)), FUN = function(x) rollmeanr(x, 2, fill = NA)))
其中任一方法都会得到如下结果:
value ma
1 0 NA
2 1 NA
3 2 1.5
4 3 NA
5 4 3.5
6 5 NA
7 6 5.5
8 7 NA
9 8 7.5
10 9 NA
11 10 9.5
英文:
Reverse it, use rollapply
with by = 2
and align = "left"
and reverse it back or with ave
reverse gl
.
library(zoo)
df <- data.frame(value=0:10)
transform(df, ma = rev(rollapply(rev(value), 2, mean, by = 2, fill = NA,
align = "left")))
# or
n <- nrow(df)
transform(df, ma = ave(value, rev(gl(n, 2, n)),
FUN = \(x) rollmeanr(x, 2, fill = NA)))
Either one gives
value ma
1 0 NA
2 1 NA
3 2 1.5
4 3 NA
5 4 3.5
6 5 NA
7 6 5.5
8 7 NA
9 8 7.5
10 9 NA
11 10 9.5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论