识别局部最小值后的局部最大值

时间:2017-02-27 20:00:51

标签: r jitter

我想要分析一些嘈杂的数据。以此处的数据为例。

set.seed(98765)
A <- seq(0, 3, 0.01)
B <- round(exp(A),digits = 2)
B <-round(ifelse(B>1.5, jitter(B, factor = 200),B),digits = 2)
#
C <-seq(3,3.5,0.01)
D <- rep(B[301],51)
D <-round(jitter(D, factor = 0.8),digits = 2)
#
E <-seq(3.5,4,0.01)
Ff <- rep(D[51],51)
Ff <-round(jitter(Ff, factor = 1.3),digits = 2)
#
G <- seq(4,5, 0.01)
H <- (-10*G)+60
H <- round(jitter(H, factor = 50),digits = 2)
#
I <- seq(5,6,0.01)
J <- 5*I-15
J <- round(jitter(J, factor = 50),digits = 2)
#
K <- seq(6,8,0.01)
L <- (-2*K)+27
L <- round(jitter(L, factor = 40),digits = 2)
#
X <- c(A,C,E,G,I,K)
Y <- c(B,D,Ff,H,J,L)
#
df1 <- data.frame(X,Y)
ggplot(df1, aes(X,Y))+geom_point()

因此,在绘图之后,我们会看到x=5周围出现最小位置,并且在我们达到局部最大值之后不久。

如何获取此局部最大值的两个最大Y值?

我可以通过指定x约束(对应于最小值)来获得最大值,但在我的数据中,实际位置会发生变化,但形状的形状保持不变。

## max value 
## max(df1$Y[df1$X>5])

1 个答案:

答案 0 :(得分:1)

这不是完整的答案,但这是一种可能提供方向的方法

#Fit a smooth spline to the data and extract y-value
dty = smooth.spline(df1$X, df1$Y)$y

#Obtain delta values for dty
delta = c(0, diff(dty))

#Plot the data as a line
plot(df1$X, df1$Y, type = "l")

#Points corresponding to zero in diff for dty are local maxima and minima (in theory)
#In practice, you may have to tweak the tolerance
points(df1$X[which(delta > -0.01 & delta < 0.01)],
         df1$Y[which(delta > -0.01 & delta < 0.01)],
         pch = 19, col = 'red')

enter image description here