rollmean与dplyr和magrittr [英] rollmean with dplyr and magrittr
本文介绍了rollmean与dplyr和magrittr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下数据:
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
我想计算滚动平均数包package oo u u u u u。。。。。。。。。滚动均值的顺序由t设定。滚动平均值应该作为新的列添加到data.frame。
I want to calculate the rolling mean (package zoo) of u per group defined by the coloumn o. The order for the rolling mean is set by t. The rolling mean should be added as a new column to the data.frame.
我想使用magrittr和dplyr。我试过
I want to use magrittr and dplyr. I tried
data %>%
group_by(o) %>%
sort(t) %>%
select(u) %>%
rollmean(3) %>%
rbind
但这不行。有可能用magrittr和dplyr来做,还是要一步一步地做?
o和t的值在我的实际数据中是可变的。
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? The values of o and t are variable in my real data.
如何填写前两行?
推荐答案
这是有帮助的:
library(dplyr)
data %>%
group_by(o) %>%
mutate(rM=rollmean(u,3, na.pad=TRUE, align="right"))
如果您想为这两列执行 u
和 v
If you want to do for both columns, u
and v
fun1 <- function(x) rollmean(x, 3, na.pad=TRUE, align="right")
data %>%
group_by(o) %>%
mutate_each(funs(fun1), u, v)
这篇关于rollmean与dplyr和magrittr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文