I'm very new both to programming and to R so please bear with me :-)I've written the following bit of code, which works perfectly well and runs through a data file with 17446 rows in about 35 seconds. I don't really have a problem with this but am sure that this could be a lot more elegant with probably the use of the tapply function. I would love to see how you experts would rewrite this more efficiently and am sure the rewrite would teach me a lot. I've included the first few rows of the output file and hopefully the code should be fairly obvious (it must be if I managed to write it!!); it's a simple filter based on the standard deviation of a subset in one column dictating the output to another column which is set up at the start of the code. If a value in the NEE column is more than 2 stdevs of the preceeding three values then the value is taken from the mean of a subset in the NEE2 column else the value is copied from the first (if that makes sense). Please also note the count variable as I need to retrieve the amount of values replaced. Hope this piques someone's interest and thanks in advance for all of your time.JonPDspke <- read.csv(file.choose())nr = nrow(Dspke)count = 0Dspke$NEE2 <- (1:nr) #creates a new column ready for input of valuesfor (i in 4:nr) {#standard deviation of the previous three values in NEEstdev <- sd(Dspke$NEE[(i-2):i]) #if stdev>2 then NEE2 value is mean of the previous 3 values in NEE2 else copy value from NEEif(stdev>=2) {  Dspke$NEE2[i] <- mean(Dspke$NEE2[(i-2):i-1])    count = count+1    }else { Dspke$NEE2[i] <- Dspke$NEE[i]  } }     write.csv(Dspke,Dspke.csv) Date_Time       NEE     NEE21 03/01/2012 13:00 -2.300000  1.000002 03/01/2012 13:30 -2.385610  2.000003 03/01/2012 14:00 -2.081935  3.000004 03/01/2012 14:30 -1.778260 -1.778265 03/01/2012 15:00 -2.409490 -2.409496 03/01/2012 15:30 -0.741030 -0.74103
More elegant filter script in R
r