increase speed for 'for loop'
Revised: ...I wonder if this could replace those two loops? Here are the results with the test vector offered in your comments:

set.seed(100);  m=rnorm(15); std_d &lt;- sd(m)
Reduce(function(y,xx){ if( abs(tail(y[!is.na(y)], 1) - xx) &gt; std_d ) {c(y,NA)}else{ 
                                                                        c(y,xx)} }, 
          m )
 [1] -0.50219235          NA -0.07891709          NA  0.11697127  0.31863009          NA  0.71453271
 [9]          NA          NA          NA          NA          NA  0.73984050          NA


Here's original test case with revised results. It is now comparing the last non-NA value to the current one and making NA if it exceeds the standard value. That other solution looked at the running sd() but your code did not do that so I just used a global sd value:

&gt; z &lt;- read.zoo(text=' "timestamp" "mesured_distance" "IFC_Code" "from_sensor_to_river_bottom"
 "1" "2012-06-03 12:30:07-05" 3188 1005 3500
 "2" "2012-06-03 12:15:16-05" 3189 1005 3500
 "3" "2012-06-03 12:00:08-05" 3185 1005 3500
 "4" "2012-06-03 11:45:11-05" 3191 1005 3500
 "5" "2012-06-03 11:30:15-05" 3188 1005 3500', tz = "")
 std_d &lt;- sd(coredata(z[,1]) )
 zx &lt;- as.numeric(coredata(z[,1]))
 coredata(z[,1]) &lt;- Reduce(function(y,xx){ 
                              if( abs(tail(y[!is.na(y)], 1) - xx) &gt; std_d ) {
                                        c(y,NA)} else { 
                                        c(y,xx)} }, 
                                  zx )
 z
                    mesured_distance IFC_Code from_sensor_to_river_bottom
2012-06-03 11:30:15             3188     1005                        3500
2012-06-03 11:45:11               NA     1005                        3500
2012-06-03 12:00:08               NA     1005                        3500
2012-06-03 12:15:16             3189     1005                        3500
2012-06-03 12:30:07             3188     1005                        3500