I have a dataset with the number of hourly visits an animal made during a period of 12 months. I want to use the Fast Fourier Transform to examine cyclical patterns and periodicity. In the past, I have used Statistica for this this; however, I would like to use R to get a plot of the spectral density vs. period. Is there an easy way to do this in R? I would like to identify 12 and 24 hr peak in activity if possible.
2 Answers
You may consider the following functions.
periodogramfromTSApackage immediately plots a periodogram.periodogramfromGeneCyclereturns a list of frequencies and estimated power spectral densities. It is a wrapper function forstats::spectrumwith some special options set.spectrumfromstatsallows you to choose the method used to estimate the spectral density: either periodogram or using autoregressive process.cpgramfromstatsplots a cumulative periodogram along with a confidence interval.
See, e.g., ?cpgram or ?spectrum for all the details and keep in mind that it is, e.g., TSA::periodogram and GeneCycle::periodogram when names of the functions coincide.
There are also plenty of examples and tutorials online on how to use those functions. See here for the usage of fft and here for an even more extensive tutorial.
Also, as you probably already know, a given time series must be detrended. Hence, use, e.g., diff(x) instead of x. And finally, the length of your time series must be divisible by 12 as to be able to identify 12 and 24 hours frequencies, it can be achieved by, e.g., x[-(1:(length(x) %% 12))], where x is a detrended time series.
- 47,421
 - 9
 - 90
 - 102
 
Use spectrum to do a spectral density analysis; also fft for the base fast Fourier transform.
- 56,353
 - 13
 - 134
 - 187
 
- 
                    1Could you elaborate a bit. First do the fft on the original data, and then use the function spectrum? – user1626688 Dec 23 '12 at 12:05
 - 
                    4no, `spectrum` is a self-contained spectral density analyzer; it calls `fft` with some pre- and post-processing and plotting. – Ben Bolker Dec 23 '12 at 14:49
 - 
                    The two examples for fft do not window the data first. Alas it is hard to find which libraries window data correctly without testing them with e.g. a ramp signal. Test to make sure. – Paul S May 15 '21 at 23:59