在函数中从标准偏差切换到移动平均值

时间:2012-06-06 01:19:18

标签: r function

我正从数据集中删除错误的数据值。直到现在我按照以下方法进行:

假设z [,1]是我的时间序列变量.e s是其中的各个元素 std_d is sd(abs( diff(z[,1], lag=1) ))

e1-e2> std_d... remove e2.
e1-e3> std_d...remove e3
e1-e4<std_d...move on to e4
e4-e5 <std_d..move on e5
e5-e6>std_d...remove e6
e5-e7<std_d...move on e7

我使用以下代码执行此操作:

   zx <- as.numeric(coredata(z[,1]))
 coredata(z[,1]) <- Reduce(function(y,xx){ 
                          if( abs(tail(y[!is.na(y)], 1) - xx) > std_d ) {
                                    c(y,NA)} else { 
                                    c(y,xx)} }, 
                              zx )

我的问题是:

我想从std_d切换,即滞后差的标准差到'移动标准偏差'。例如,如果我们检查e20,std_d应该是 - &gt; std之前的15个元素和之后的15个元素的差异,滞后= 1。

我在考虑在动物园里使用滚动平均值。但我无法在上述功能中使用它。 怎么办呢?

感谢您的时间和考虑。 以下是示例数据:

           "timestamp" "mesured_distance" "IFC_Code" "from_sensor_to_river_bottom"
   "1" "2012-06-04 21:30:09-05" 4818 995 5030
   "2" "2012-06-04 21:15:11-05" 4820 995 5030
   "3" "2012-06-04 21:00:10-05" 4818 995 5030
   "4" "2012-06-04 20:45:10-05" 4817 995 5030
   "5" "2012-06-04 20:30:09-05" 8816 995 5030
   "6" "2012-06-04 20:15:09-05" 4816 995 5030
   "7" "2012-06-04 20:00:08-05" 4811 995 5030
   "8" "2012-06-04 19:45:07-05" 15009 995 5030
   "9" "2012-06-04 19:30:07-05" 4810 995 5030
   "10" "2012-06-04 19:15:09-05" 4795 995 5030

1 个答案:

答案 0 :(得分:1)

也许......在没有数据的情况下未经测试:

zx <- as.numeric(coredata(z[,1]))
coredata(z[,1]) <- Reduce(function(y,xx){ 
                          if( length(y) <15) {c(y,xx) } else {
                          if( abs(tail(y[!is.na(y)], 1) - xx) > std(tail( y, 15) ) {
                                    c(y,NA)} else { 
                                    c(y,xx)}                                       } 
                                          }, 
                              zx )

无法确定我是否在没有测试的情况下正确匹配了parens和braces

相关问题