r中第二因子移动平均数

i5desfxk  于 2023-06-03  发布在  其他
关注(0)|答案(2)|浏览(166)

我使用这个作为一个例子(Calculating moving average),我已经成功地纳入我的代码。我需要计算滚动平均值和滚动中位数(我已经做了),但我的数据集是巨大的,我需要添加一个辅助变量来过滤这个。在下面的示例中,他们计算了10天数据集的滚动平均值。如果不同的地点有10天的时间,我们需要根据这些不同的地点计算10天的滚动平均值,会发生什么?

library(tidyverse)
library(zoo)

some_data = tibble(day = 1:10)
# cma = centered moving average
# tma = trailing moving average
some_data = some_data %>%
mutate(roll_mean = rollmean(day, k = 3, fill = NA)) %>%
mutate(roll_median = rollmedian(day, k = 3, fill = NA, align = "right"))
some_data
kr98yfug

kr98yfug1#

您可以按位置分组:

library(tidyverse)
library(zoo)

some_data <- rbind(tibble(day = 1:5,location = c(rep("A",5))),
                   tibble(day = 1:5,location = c(rep("B",5))))

some_data <- some_data %>% group_by(location) %>%
  mutate(roll_mean_left = rollmean(day, k = 3, fill = NA, align='left'),
         roll_mean_right = rollmean(day, k = 3, fill = NA, align='center'),
         roll_median_center = rollmedian(day, k = 3, fill = NA, align = 'right'))

some_data

滚动函数会为每个位置重新初始化。
注意滚动窗口如何根据align参数移动:

day location roll_mean_left roll_mean_right roll_median_center
   <int> <chr>             <dbl>           <dbl>              <dbl>
 1     1 A                     2              NA                 NA
 2     2 A                     3               2                 NA
 3     3 A                     4               3                  2
 4     4 A                    NA               4                  3
 5     5 A                    NA              NA                  4
 6     1 B                     2              NA                 NA
 7     2 B                     3               2                 NA
 8     3 B                     4               3                  2
 9     4 B                    NA               4                  3
10     5 B                    NA              NA                  4
yx2lnoni

yx2lnoni2#

小提示:

mutate(roll_mean_left = rollmean(day, k = 3, fill = NA, align='left'),
     roll_mean_right = rollmean(day, k = 3, fill = NA, align='center'),
     roll_median_center = rollmedian(day, k = 3, fill = NA, align = 'right'))

是有点误导,我想这是注定的

mutate(roll_mean_left = rollmean(day, k = 3, fill = NA, align='left'),
     roll_mean_right = rollmean(day, k = 3, fill = NA, align='right'),
     roll_median_center = rollmedian(day, k = 3, fill = NA, align = 'center'))

注意“align=”子句的更改以匹配变量名。

相关问题