Last active
December 16, 2015 03:39
-
-
Save iant/5371391 to your computer and use it in GitHub Desktop.
Determining periodicity of a time series using spectrum analysis using R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Where 'ts' is the time series (without transient behavior) | |
# a <- as.data.frame(cbind(spectrum(ts)$freq,spectrum(ts)$spec)) | |
# b <- order(a[2], decreasing=TRUE)[1] | |
# 1/a$V1[b] # !If this is the same as length(ts) then periodicity is 0(zero) | |
periodicity <- function(ts){ | |
if (length(unique(ts))==1){ | |
# No need for spectrum analysis as all values are same. Periodicity is zero. | |
return(0) | |
} else { | |
a <- as.data.frame(cbind(spectrum(ts)$freq,spectrum(ts)$spec)) | |
b <- order(a[2], decreasing=TRUE)[1] # Find the index of the spec with highest frequency | |
c <- 1/a$V1[b] # Calculate number of cycles | |
if (c==length(ts)+1){ | |
return(0) # Periodicity length is same as ts return periodicity 0 | |
}else{ | |
return(1/a$V1[b]) # Return periodicity | |
} | |
} | |
} | |
# sample time series | |
ts <- rep(c(1:1),100) # 0 periodicity | |
ts <- rep(c(1:2),100) # 2 cycle | |
ts <- rep(c(1:3),100) # 3 cycles | |
ts <- rep(c(1:4),100) # 4 cycles | |
ts <- rep(c(1:5),100) # 5 cycles | |
ts <- rep(c(2:11),100) # 10 cycles | |
ts <- rnorm(100, 1, 100) # Stochastic | |
periodicity(ts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment