[R] Find maxima of a function

Ismail SEZEN sezenismail at gmail.com
Sat Aug 26 21:13:46 CEST 2017


> On 26 Aug 2017, at 16:39, niharika singhal <niharikasinghal1990 at gmail.com> wrote:
> 
> Hi,
> 
> Thanks for your mail, and time
> 
> It is not working for some arguments, when mean value is like >6.
> 
> 
> case
> 
> mc0 <- c(0.08844446,0.1744455,0.1379778,0.1209769,0.1573065,0.
> 1134463,0.2074027)
> 
> rv <-UnivarMixingDistribution(Norm(486.4255, 53.24133),
> 
>                              Norm(664.0713, 3.674773),
> 
>                              Norm(669.0484, 4.101381),
> 
>                              Norm(677.1753, 4.869985),
> 
>                              Norm(683.2635, 7.288175),
> 
>                              Norm(727.6229, 37.64198),
> 
>                              Norm(819.2011, 57.06655),
> 
>                              mixCoeff=mc0/sum(mc0))
> 
> plot(rv, to.draw.arg="d")
> 
> 
> I am getting 731.1345 from the code you have provide
> 
> 
> It is part of a code, so it was difficult to write a reproducible code
> 
> I have tried to use optimr but it gives me the local maxima, now I am
> struck with the problem of how to get the global maxima
> 

This is basically an optimization problem so it’s nothing to do with distr package and UnivarMixingDistribution function. Also I’m not able to install distr package because of an error. Can you create an example by rnorm function? or use dput to share x and y outputs of UnivarMixingDistribution function and I can look for the issue.

Also You might have multiple maximas has same maximum y-values (for instance, y = sin(x)) and this definition is relevant to defined interval. For instance again, we can talk about a global extremum for a function like y = ax^2+bx + c. We know we will have only a single extremum point (maxima or minima). For higher order functions, we can talk about only local maximas. So, I assume you want to obtain maximum one of this local maximas, right?

If yes, why don’t we find the maximum y-value and corresponding x-value as follows?

y <- c(1,2,3,4,3,2,3,4,5,6,7,8,9,8,7,6,5,6,7,6,5)
x <- 1:length(y)

fun <- splinefun(x = x, y = y, method = "n")
x2 <- seq(1, max(x), 0.1)
y2 <- fun(x2)
plot(x, y, type = "l")
lines(x2, y2, col = "red")

max.x <- optimize(fun, interval = range(x), maximum = TRUE)
print(max.x) # x coordinate of global maximum of y by spline and optimize
x[which(y == max(y))] # global maximum of dicrete x-y vectors


spline function uses cubic spline method to obtain the undefined values in a discrete series and optimize function calculates EXACT LOCATION of the extremum. I suspect we have a communication failure :)



More information about the R-help mailing list