More elegant filter script in R
The embed function is well-suited for constructing trailing vectors by row:

 Dspke[ , paste0("E3", 1:3)] &lt;- NA     # create columns to hold the trailing values
 Dspke[4:nrow(Dspke), 5:7] &lt;- embed(Dspke$NEE, 3)
 Dspke$NEE3 &lt;- ifelse( apply(Dspke[,5:7], 1, sd) &gt;2,   #test
                             rowMeans(Dspke[,5:7]),   # result if TRUE
                             Dspke[,"NEE"])           # result if FALSE


I see the count vector being created but cannot tell from your description what it is supposed to do. Perhaps you should store the value of:

&gt; apply(Dspke[,5:7], 1, sd) &gt; 2)
    1     2     3     4     5     6 
   NA    NA    NA FALSE FALSE FALSE 


(Not a very good test of the code presented by the data since all of the tests are FALSE.)