一千萬個為什麽

搜索

尋找局部最大值和最小值

我正在尋找一種計算有效的方法來查找R中大量數字的局部最大值/最小值。 希望沒有 for 循環......

例如,如果我有一個像 1 2 3 2 1 1 2 1 這樣的數據文件,我希望函數返回3和7,它們是局部最大值的位置。

最佳答案

diff(diff(x)) (or diff(x,differences=2): thanks to @ZheyuanLi) essentially computes the discrete analogue of the second derivative, so should be negative at local maxima. The +1 below takes care of the fact that the result of diff is shorter than the input vector.

edit: added @Tommy's correction for cases where delta-x is not 1...

tt <- c(1,2,3,2,1, 1, 2, 1)
which(diff(sign(diff(tt)))==-2)+1

我的建議( http://statweb.stanford.edu/~tibs/PPC/Rdist/ )適用於數據較嘈雜的情況。

轉載註明原文: 尋找局部最大值和最小值