Detecting Seasonality in R

自古美人都是妖i 提交于 2019-12-11 11:15:31

问题


Problem: Detecting cyclical patterns in daily data using periodogram and FFT in R.

The issue is how to code in R the periodogram to detect monthly, quarterly, semi-annual, annual..etc cyclical patterns in the data. In other words I need to detect the existence of cyclical patterns for low frequencies ( ie: 1 year=> 2*pi/365, 6 months = > 4*pi/365, etc)

Reproducible Example:

 library(weatherData)
 w2009=getWeatherForYear("sfo",2009)
 w2010=getWeatherForYear("sfo",2010)
 w2011=getWeatherForYear("sfo",2011)
 w2012=getWeatherForYear("sfo",2012)
 w2013=getWeatherForYear("sfo",2013)
 w2014=getWeatherForYear("sfo",2014)
 w=rbind(w2009,w2010); w=rbind(w,w2011); w=rbind(w,w2012) 
 w=rbind(w,w2013); w=rbind(w,w2014)

 # Next we analyze the periodograms
 # This is IMAGE 1
 TSA::periodogram(w$Max_TemperatureF)
 # Next: I dont really know to use this information
 GeneCycle::periodogram(w$Max_TemperatureF)
 # Next THIS IS IMAGE 2
 stats::spectrum(w$Max_TemperatureF)
 # I also tried . This is IMAGE 3
 f.data <- GeneCycle::periodogram(tmax)
 harmonics <- 1:365
 plot(f.data$freq[harmonics]*length(tmax),]
      f.data$spec[harmonics]/sum(f.data$spec),
      xlab="Harmonics (Hz)", ylab="Amplitute Density", type="h")

After reading the answers, I did:

 per <- TSA::periodogram(w$Max_TemperatureF,lwd = 1)
 x <- which(per$freq < 0.01)
 plot(x = per$freq[x], y = per$spec[x], type="s")

My question is what does it all mean? Do we have a seasonality cycle?


回答1:


If you are looking for a long periods (365 days) you will find it under very low frequency

> 1/365
[1] 0.002739726

You can actually see a peak on the left of your first image at this value. Filter to lower frequencies if you want to zoom-in:

per <- TSA::periodogram(w$Max_TemperatureF,lwd = 1)
x <- which(per$freq < 0.01)
plot(x = per$freq[x], y = per$spec[x], type="s")

Another way to search for periodicity is auto-correlation estimation (acf):

acf(w$Max_TemperatureF, lag.max = 365*3)

See also seasonal decomposition:

ts1 <- ts(data = w$Max_TemperatureF, frequency = 365)
plot( stl(ts1, s.window = "periodic"))


来源:https://stackoverflow.com/questions/28817794/detecting-seasonality-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!