简体   繁体   中英

Error in my math formula for implementing CUSUM in R

I'm trying to implement a check for decreasing values of avg temperatures to see when the temperature starts falling. See the chart of temperatures here:

在此处输入图像描述

Here is the formula I'm trying to implement:

在此处输入图像描述

Here is my code to implement that formula:

temps <- read.delim("temps.txt")
date_avgs <- rowMeans(temps[2:length(temps)], dims=1, na.rm=T)
mu <- 87
threshold <- 86
constant <- 3

date_avgs
S <- 0 * date_avgs
for (i in 2:length(date_avgs)) {
  value <- S[i-1] + (mu - date_avgs[i] - constant)
  cat("\nvalue", value, "si", date_avgs[i], i)
  S[i] <- max(0, value)
  if(S[i] >= threshold){
    #Once I hit this for the first time, that indicates at this index the temp is decreasing
    cat("\nDecreased past my threshold!!!", S[i] ,i)
  }
}

But I'm not able to detect the change as I expect. My formula doesn't get over the threshold until index 108, when it should get there around index 60.

Here is the plot of my S (or CUSUM) values:

在此处输入图像描述

Any ideas what I'm doing wrong in my formula?

I think the problem is mu <- mean(date_avgs) basically means of all the observations. But mu should be "mean of X if no change" . Thus mu should be about 87 but according your code and plotted data seems to be 80 or less.

# simulated data
set.seed(4422)
date_avgs <- c(runif(60, 84, 92), 88-(1:50)-rnorm(50,0,4))
plot(date_avgs)
# setting constants
mu <- 87
threshold <- 86
constant <- 3

模拟数据

# after running for cycle
Index <- match(S[S >= threshold][1], S) 
Index
[1] 75
# for data
> date_avgs[74]
[1] 73.41981

# Considering a lower threshold 
# (as maximum allowable difference to detect trend 2 * C)
mu <- 87
threshold <- 6 # arbitrary 
constant <- 3
# after running for cycle
Index <- match(S[S >= threshold][1], S) 
Index
[1] 66 

So I think code is fine, maybe the interpretation is not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM