Search code examples
rmoving-averagerolling-average

How can I get information about moving average?


I want to calculate moving average for my project. But I don't understand this blew codes. How can get more information about moving average codes?

cx <- c(0, cumsum(ifelse(is.na(x), 0, x)))
cn <- c(0, cumsum(ifelse(is.na(x), 0, 1)))0
rx <- cx[(n+1):length(cx)] - cx[1:(length(cx) - n)]
rn <- cn[(n+1):length(cx)] - cn[1:(length(cx) - n)]
rsum <- rx / rn

Solution

  • If the question is asking to explain the code then it is taking the moving average of length n of the vector x. For example, if there are no NA's and n=2 then the first few elements of the output are (x[1] + x[2])/2, (x[2] + x[3])/2, etc.

    n <- 2
    x <- c(1, 3, 4, 7, 9)
    cx <- c(0, cumsum(ifelse(is.na(x), 0, x)))  # 0  1  4  8 15 24
    cn <- c(0, cumsum(ifelse(is.na(x), 0, 1)))  # 0 1 2 3 4 5
    rx <- cx[(n+1):length(cx)] - cx[1:(length(cx) - n)]  #  4  7 11 16
    rn <- cn[(n+1):length(cx)] - cn[1:(length(cx) - n)]  # 2 2 2 2
    rsum <- rx / rn  # 2.0 3.5 5.5 8.0
    

    cx is 0 followed by the cumulative sum of x except NA's are replaced with 0 in calculating the cumulative sum.

    cn is 0 followed by the cumulative number of non-NA's.

    rx is the cumulative sum minus the cumulative sum n positions back.

    rn is the number of non-NA's minus the number of non-NAs n positions back.

    rsum is the ratio of the last two.