r - 如何计算向量中的渐进平均值但在满足条件时重新启动?
问题描述
给出以下向量
x<-c(0,0,0,5.0,5.1,5.0,6.5,6.7,6.0,0,0,0,0,3.8,4.0,3.6)
我想要一个具有累积平均值的向量,例如
cumsum(x)/seq_along(x)
但每次两个后续值之间的差值大于 1.3 或小于 -1.3 时都会重新开始计算。我的目标是获得像
d<-c(0,0,0,5,5.05,5.03,6.5,6.6,6.37,0,0,0,0,3.8,3.9,3.8)
谢谢
解决方案
您可以使用cumsum(abs(diff(x)) > 1.3))
定义组,用于在每次差值大于 1.3 或小于 -1.3 时aggregate
重新启动。cumsum(x)/seq_along(x)
unlist(aggregate(x, list(c(0, cumsum(abs(diff(x)) > 1.3))),
function(x) cumsum(x)/seq_along(x))[,2])
# [1] 0.000000 0.000000 0.000000 5.000000 5.050000 5.033333 6.500000 6.600000
# [9] 6.400000 0.000000 0.000000 0.000000 0.000000 3.800000 3.900000 3.800000
推荐阅读
- ios - 'LGsideMenucontroller' 未在 swift 4 的所有视图控制器中打开
- java - 如何修复“删除令牌连接超时后重新连接 SunPKCS11”
- android - 'java.lang.String' 在 Android 中已弃用
- php - 如何使用 PHP 在会话中传递单选按钮的值?
- node.js - 在 Elasticsearch JS 中使用复合查询面临困难
- javascript - Bootstrap 折叠滚动到底部问题
- android - 除非重叠文本视图,否则是否可以在约束布局中将图标居中
- spring - RabbitMQ:通道关闭:连接错误
- c# - 在此处添加构造函数逻辑
- sql - SQL查找几乎相同的值