How to find local maximum in R from graph

杀马特。学长 韩版系。学妹 提交于 2019-12-13 01:29:13

问题


I'm having a problem with my coding. I'm supposed to

  1. Plot a graph of this equation [y=f(x)] where f(x) = (10*((x-1)^2)^(1/3))/(x^2 + 9) for 10001 values of x between (and including) -5 and 5

  2. Among the 10001 x values in a, find the two local maximums of f(x).

I tried doing this :

# question1
x <- seq(-5,5,length=10001)
y <- (10*((x-1)^2)^(1/3))/(x^2 + 9)

plot(x,y) # This will produce a graph with two max point

# question2
x[which.max(y)]
y[which.max(y)]

however, i only get the coordinates one of the maximum point and clueless as to how do i get another maximum point.


回答1:


You can use find_peaks from package ggpmisc.

library(ggpmisc)
x[ggpmisc:::find_peaks(df$y)]
y[ggpmisc:::find_peaks(df$y)]

The output is:

[1] -1.5  3.0
[1] 1.6373473 0.8818895

Note that the function find_peaks is noted as internal. You therefore need to access it using :::.

You can further parametrize the call to find_peaks using the span and strict argument. See ??find_peaks for details.

You can also directly plot this using the ggplot2 and ggpmisc packages:

x <- seq(-5,5,length=10001)
y <- (10*((x-1)^2)^(1/3))/(x^2 + 9)
df <- data.frame(x = x, y = y)
ggplot(data = df, aes(x = x, y = y)) + geom_line() + stat_peaks(col = "red")



来源:https://stackoverflow.com/questions/55342232/how-to-find-local-maximum-in-r-from-graph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!