Following this answer, I'm trying to find the local minima of a function. Here is what I'm doing:
require(ggplot2)
require(zoo)
x <- seq(0, 25, by=0.1)
y <- sin(x)
my.df <- data.frame(x, y)
xz <- as.zoo(y)
rxz <- zoo::rollapply(xz, width = 20, align = "center", function(x) which.min(x)==2)
indexes <- index(rxz)[coredata(rxz)]
indexes
ggplot(my.df, aes(x, y)) + geom_line() + geom_vline(xintercept = my.df$x[indexes])
Plotting the results gives:
I guess the x offset is due to the width I use, but can't figure out why this happens, as rollapply supposed to use a centred rolling window.
require
wrong: it never stops following code when the package is not available, which is almost never what is intended. Either userequire
and check the return value, or uselibrary
. Refs: stackoverflow.com/a/51263513 – r2evans