Skip to content

Instantly share code, notes, and snippets.

@omartinez182
Created June 19, 2020 18:11
Show Gist options
  • Save omartinez182/6938dc45cceeef85fd064f999efde83c to your computer and use it in GitHub Desktop.
Save omartinez182/6938dc45cceeef85fd064f999efde83c to your computer and use it in GitHub Desktop.
Understanding Time Series Analysis with R - Snippet 6
df <- data
Y <- 2 #2 is the position of our "sales" column in the data frame
k <- 4 #k is equal to the size of the subset
#Array with all of the raws of 'Y'
arr <- df[, Y]
#Empty array to store the values of the moving averages
MM<-rep(NA, length(arr))
SI <- rep(NA, length(arr))
index <- k-1
for(i in c(1:length(arr))){
if(i <= length(arr) -k+1){
block <- mean(arr[seq(i, i+(k-1))])
MM[index] <- block
SI[index] <- arr[index]/block #Seasonality + Irregular Component
index <- index+1
}
}
dfOut <- data.frame(df, MM=MM, SI=SI)
#Seasonality
varY<-c()
for(j in c(1:k)){
varX <- seq(j, length(arr), by=k)
varY <- c(varY, mean(dfOut[varX, 4], na.rm=T))
}
varY<- rep(varY, k+1)
dfOut <- data.frame(dfOut, S=varY)
dfOut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment