r - 带动态条件的条件累加和
问题描述
下午好,我正在尝试用“扭曲”创建一个累积平均值 - 我只想对当前日期之前的字段进行平均(可能有相同日期的字段)
我使用几个自定义创建的函数成功地做到了“肮脏的方式”,但它花费的时间太长而且效率非常低 - 我很确定有更好的方法。
我在想一些事情:
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
解决方案
这可以实现为 SQL 中的复杂自联接。对于连接行中的每行平均值,这会将所有具有较小Date
amd 的行连接到每一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
推荐阅读
- c++ - 以双引号将字符数组传递给函数
- selenium - 在 Chrome 浏览器中使用 ('click' selenium-java and sendKeys(Keys.ENTER)) 单击按钮时,页面挂起并给出“Aw,snap”错误
- javascript - 仅过滤 1 个菜单
- reactjs - 通过 webpack 编译应用程序时加载程序问题
- angular - 通过 angular4 在 body 上附加模态弹出窗口
- git - 带有 git-http-backend 的 nginx:具有 www-data 用户的 `git push` 的访问权限不足
- docker - 尝试将扫描实用程序添加到 Docker 映像
- r - ClusterProfiler head(GroupGO) 什么也没显示
- python - 如何使用 OpenCV (Python) 在不损失质量的情况下更改特定颜色?
- android - 如何在动态视图中添加/获取数据?