There is any R packages for calculation period of some function? I am looking for r-function like this:
x <- seq(0, 50, by = 0.05)
y <- sin(x)
p <- calcPeriod(x, y) # result = 2pi
There is any R packages for calculation period of some function? I am looking for r-function like this:
x <- seq(0, 50, by = 0.05)
y <- sin(x)
p <- calcPeriod(x, y) # result = 2pi
I think you are looking for something along the lines of a Fast Fourier Transform. I'm no expert, but I think you can do something along the lines of the following:
x <- seq(0, 50, by = 0.05)
y <- sin(x)
calcPeriod <- function(x, y){
incr <- x[2] - x[1]
tmp <- spectrum(y, plot=FALSE)
p <- (1/tmp$freq*incr)[which.max(tmp$spec)] # max of spectrum
p
}
calcPeriod(x,y) # equals 6.4
The function spectrum
is actually a wrapper function for spec.pgram
and spec.ar
. Use with caution since the calcPeriod
function is actually only identifying the maximum periodicity. For unevenly sampled series, a least-squares specrtal analysis would also identify the dominant periodicity (example link).
Paul H.'s answer reminded me that, if you prefer not to deal with Fourier analysis, you could always run nls(y~sin(k*x))
or an enhanced version thereof. This does assume you know in advance there's only one frequency in your data.
I'll put my usual plug here for Eureqa
, easily found at Cornell.edu via Google.
I am not aware of such a function myself, but you could use optim
to optimize a cost function which takes the period as a parameter. optim
would then tweak the period until an optimal fit was acquired. This is not very hard to do, and you can wrap this into a function calcPeriod
yourself.