簡體   English   中英

如何計算向量中的漸進平均值但在滿足條件時重新啟動?

[英]How to calcualte the progressive mean in a vector BUT restarting when a condition is met?

給出以下向量

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

也許您可以嘗試ave + findInterval如下所示

ave(x,findInterval(seq_along(x),which(abs(diff(x))>1.3)+1),FUN = function(v) cumsum(v)/seq_along(v))

這使

 [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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM