简体   繁体   English

带有 dplyr 和 magrittr 的 rollmean

[英]rollmean with dplyr and magrittr

Given the following data:鉴于以下数据:

    set.seed(1)
    data <- data.frame(o=c('a','a','a','a','b','b','b','b','c','c','c','c'), t=c(1,2,3,4,1,2,3,4,1,2,3,4), u=runif(12), v=runif(12))
    data
       o t          u         v
    1  a 1 0.26550866 0.6870228
    2  a 2 0.37212390 0.3841037
    3  a 3 0.57285336 0.7698414
    4  a 4 0.90820779 0.4976992
    5  b 1 0.20168193 0.7176185
    6  b 2 0.89838968 0.9919061
    7  b 3 0.94467527 0.3800352
    8  b 4 0.66079779 0.7774452
    9  c 1 0.62911404 0.9347052
    10 c 2 0.06178627 0.2121425
    11 c 3 0.20597457 0.6516738
    12 c 4 0.17655675 0.1255551

I want to calculate the rolling mean (package zoo) of u per group defined by the coloumn o.我想计算由 o 列定义的每组 u 的滚动平均值(包动物园)。 The order for the rolling mean is set by t.滚动均值的阶数由 t 设置。 The rolling mean should be added as a new column to the data.frame.滚动平均值应作为新列添加到 data.frame 中。

I want to use magrittr and dplyr.我想使用 magrittr 和 dplyr。 I tried我试过

    data %>%
      group_by(o) %>%
      sort(t) %>%
      select(u) %>%
      rollmean(3) %>%
      rbind

But this won't work.但这行不通。 Is it possible to do it with magrittr and dplyr or do I have to do it step by step?是否可以用 magrittr 和 dplyr 来完成,还是我必须一步一步地完成? The values of o and t are variable in my real data. o 和 t 的值在我的真实数据中是可变的。

How do I fill the first two rows?如何填充前两行?

May be this helps:可能这有帮助:

library(dplyr)
library(zoo)
data %>%
group_by(o) %>%
mutate(rM=rollmean(u,3, na.pad=TRUE, align="right"))

If you want to do for both columns, u and v如果你想对两列都做, uv

fun1 <- function(x) rollmean(x, 3, na.pad=TRUE, align="right")
data %>% 
group_by(o) %>% 
mutate_each(funs(fun1), u, v)

A more flexible wrapper comes from the rowr package.更灵活的包装器来自rowr包。 This allows for windows of different size within your initial data.这允许在初始数据中使用不同大小的窗口。

data %>% 
group_by(o) %>% 
mutate(MEANS = rollApply(u, fun=mean, window=3, align='right'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM