使用dplyr和RcppRoll计算所有固定的窗口平均值 [英] Compute all fixed window averages with dplyr and RcppRoll

查看:206
本文介绍了使用dplyr和RcppRoll计算所有固定的窗口平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用dplyr和RcppRoll计算所有(或至少许多)固定窗口平均值。例如,如果我想根据前4、5和6个时间步长的风暴数据计算平均风速,则可以使用以下方法:

I would like to compute all (or at least many) fixed window averages using dplyr and RcppRoll. For example, if I want to compute the average wind speed from the storms data for the previous 4, 5, and 6 timesteps, I can use the following:

library(dplyr)
library(RcppRoll)

set.seed(1)
storms <- storms[storms$name %in% sample(storms$name, size = 4),]

storms %>%
  select(name, year, month, day, hour, wind) %>%
  group_by(name) %>%
  arrange(name, year, month, day, hour) %>%
  mutate_at("wind", .funs = funs(
    "avg_4" = roll_meanr(., n = 4, fill = NA),
    "avg_5" = roll_meanr(., n = 5, fill = NA),
    "avg_6" = roll_meanr(., n = 6, fill = NA)
  ))

这行得通,但是,如果我想计算2到20的窗口的所有固定窗口平均值,我就厌倦了将行复制并粘贴到 funs()

This works, however if I wanted to compute all of the fixed window averages for windows of 2 through 20, I'd get tired of copying and pasting the rows inside of funs().

似乎我应该能够对此进行参数化,但是我还没有弄清楚如何做。

It seems like I should be able to parameterize this somehow, but I haven't yet figured out how.

推荐答案

使用Base R,希望对您有所帮助:

Using Base R, I hope it help:

storms_wind <- storms %>%
    select(name, year, month, day, hour, wind) %>%
    group_by(name) %>%
    arrange(name, year, month, day, hour)

multi_avg <- function(df, start, end) {
                 for(i in (strat:end)){
                 varname <- paste("avg", i , sep="_")
                 df[[varname]] <- with(df, roll_meanr(wind, n = i, fill = NA))
                }
             df
           }


multi_avg(df=storms_wind, start=4,end=20) 

这篇关于使用dplyr和RcppRoll计算所有固定的窗口平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆