0

我有包含两列(时间,结果)的数据。对于每一秒,我对“结果”都有不同的价值。如果超过给定条件,我想每秒检查“结果”的值。根据先前的平均值,“结果”的每个值的条件都在变化。先前的平均值是根据以下指数加权移动平均值 (EWMA) 计算得出的:

μn = μn−1 + (1 − lambda)Xn , 

lambda is the EWMA factor (for this example use 0.2) 
μn−1 is the mean value calculated from measurements prior to record n.
μn   is the mean. 
Xn   is the value of 'Result' in the nth record.
n    is number of records in the df

条件是:

g 是每次条件为真时递增的变量。

if (Xn > (1.5)μn−1) {
  g<-g+1
}

必须对数据中的所有记录执行此逻辑。

这是MWE:

readFile<- read.table("data.tr",header=F, stringsAsFactor=F)
colnames(readFile)<-c("time","Results")
df<-data.frame(Time=readFile$time,Results=readFile$Results)

#The data looks like (df);
 Time Results
   1     10
   2     15
   3     15
   4     10
   5     10
   6     30
   7     15
   8     25
   9     40
  10     22
  11     48
  12     50
  13     30
  14     40
  15     64
  16     46
  17     30
  18     10
  19     17
  20     53
  #define variables
  g<-0
  result<-0
  previousAverage<-0

  for(i in df){
   result<-df&Results[i]
   # Here I'm confused how to make the recursive call !!
   #I'm assuming the average should be returned from a separate method 
   #(i.e AverageCalculation) and use in the condition

   condition <- (1.5) * previousAverage
   if ( result > condition){
       g<-g+1
    }
  }

我发现“qcc”包计算 EWMA 应该简化计算。但是,我想使用上面的等式。对我来说困难的部分是如何计算从第一条记录到第 n-1 条记录的平均值并不断变化?我如何保持当前的记录值。

有什么建议么?!!!

4

1 回答 1

0

在你的循环之外,初始化 mu 和滞后的列。

mu = 0
df$prevmu <- 0

然后循环遍历行,

for(i in 1:nrow(df)) {
  df$prevmu[i] <- mu
  mu <- mu + (1 - lambda) * df$Result[i]
}

现在您可以计算 g:

g <- with(df, sum(Results > 1.5 * prevmu))
于 2013-10-25T20:09:23.013 回答