Skip to content

calculate a "rolling mean" including standard deviation

2 messages · Tagmarie, Rui Barradas

#
Hello everyone, 

I have a data frame somewhat like this one: 

myframe <- data.frame (Timestamp=c( "24.09.2012 06:00", "24.09.2012 07:00",
"24.09.2012 08:00", 
                                    "24.09.2012 09:00", "24.09.2012 10:00",
"24.09.2012 11:00", 
                                    "24.09.2012 12:00", "24.09.2012 13:00",
"24.09.2012 14:00"),
                        distance =c(9,9,9,4,5,9,4,5,5 ) )
myframestime <- as.POSIXct (strptime(as.character(myframe$Timestamp),
"%d.%m.%Y %H:%M"), tz="GMT")
myframe2 <- cbind (myframestime, myframe)
myframe2$Timestamp <- NULL  
myframe2

This is what I want to do: 
1.) calculate the mean and the standard deviation for "distance" from the
last too rows (at 13:00 and 14:00)
2.) compare the value for distance one row earlier (12:00). If that value is
in the range of the previously calculated mean + sd I want to include the
value and calculate a new mean and a new sd. If there is one value which is
not in the range I want to exclude/ignore the value. If there are two
subsequent values which are not in the range then I want to stopp the
calculation (or at least mark the point by including e.g. NAs). 

Does anyone know how to do that? 





--
View this message in context: http://r.789695.n4.nabble.com/calculate-a-rolling-mean-including-standard-deviation-tp4653303.html
Sent from the R help mailing list archive at Nabble.com.
#
Hello,

Something like this?


d <- myframe2$distance
n <- length(d)
mu <- rep(NA, n - 1)
mu[n - 1] <- m <- mean(d[(n - 1):n])
s <- sd(d[(n - 1):n])
ex <- 0
for(i in rev(seq_len(n))[-(1:2)]){
     if(d[i] < m + s){
         ex <- 0
         mu[i] <- m
     }else{
         ex <- ex + 1
         if(ex >= 2) break
     }
     m <- mean(d[i:n])
     s <- sd(d[i:n])
}
mu


Hope this helps,

Rui Barradas
Em 17-12-2012 14:55, Tagmarie escreveu: