Search code examples
rfunctionmaxlocal

How to find local maximum in R from graph


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.


Solution

  • 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")
    

    enter image description here