首页 > 解决方案 > 带动态条件的条件累加和

问题描述

下午好,我正在尝试用“扭曲”创建一个累积平均值 - 我只想对当前日期之前的字段进行平均(可能有相同日期的字段)

我使用几个自定义创建的函数成功地做到了“肮脏的方式”,但它花费的时间太长而且效率非常低 - 我很确定有更好的方法。

我在想一些事情:

averages <- DB %>% group_by(field1,field2) %>% mutate(Avg=cummean(???*value1)))

我如何访问cummean 功能的当前观察

我走的路线是为每个带有循环的子集创建一个逻辑向量

for (i in 1:length(datevector)-1)
    logicalvector[i] <- datevector[length(datevector)]>datevector[i]
  logicalvector[length(datevector)]=F

并在另一个函数中使用它来计算平均值

一个简单的例子是:

df <- data.frame(id=1:5,Date=as.Date(c("2013-08-02","2013-08-02","2013-08-03","2013-08-03","2013-08-04")),Value=c(1,4,5,2,4))

id  Date    Value     accum mean
1  02/08/2013     1         0
2  02/08/2013     4         0
3  03/08/2013     5        2.5
4  03/08/2013     2        2.5
5  04/08/2013     4         3

Explanation:
there are no observation with a prior date for the first 2 observations so the mean is 0
the 3rd observation averages the 1st and 2nd, so does the 4th.
the 5th observation averages all

标签: r

解决方案


这可以实现为 SQL 中的复杂自联接。对于连接行中的每行平均值,这会将所有具有较小Dateamd 的行连接到每一Value行。 coalesce用于在平均值为 Null 的情况下分配 0。

library(sqldf)

sqldf("select a.*, coalesce(avg(b.Value), 0) as mean
  from df as a 
  left join df as b on b.Date < a.Date
  group by a.rowid")

给予:

  id       Date Value mean
1  1 2013-08-02     1  0.0
2  2 2013-08-02     4  0.0
3  3 2013-08-03     5  2.5
4  4 2013-08-03     2  2.5
5  5 2013-08-04     4  3.0

推荐阅读