Problem integrating a function in R

Hello! I want to do this formula in R:
With k=1
Where F(x) is the distribution function of x and f(x) is the density function of x.
In my programming I called x emhi and x-T(x) edhi.

I did:

distx <- function (x){plnorm(x, meanlog=mean(log(emhi)), sdlog=sd(log(emhi)), lower.tail = TRUE, log.p = FALSE)}
densx <- function (x){dlnorm(x, meanlog=mean(log(emhi)), sdlog=sd(log(emhi)), log = FALSE)}n<-1
integral <- function(edhi) {
for (x in edhi) {
return (edhi[n]*(1-distx(emhi[n]))*densx(emhi[n]))
wy <- integrate(integral, 0, Inf)

However it's telling me "evaluation of function gave a result of wrong length".
Where is the mistake? How can I do it?
Thank you!!!

In R when you return from a function, you leave from that function; hence any code that might have been written into a function after return executes is irrelevant/ignored; hence n=n+1 never happens.

So, should I put n=n+1 before return?

I don't know; I don't have training to follow that formula definition.

In addition to the point @nirgrahamuk makes, you have the return inside the for loop. The first time return is executed, the function comes to an end. So you are only getting one point.

You probably want to create the whole vector in the for loop, and then return the vector outside that loop.

Yes, I figured that out too.
However I still can't integrate the function. Any idea why?

No, but maybe post your fixed up code and someone will see something.

That's quite a complicated integrand. How about starting with a much reduced integrand, integrating it, and then slowly building up your integrand until you see the first time you get an error?

It looks like you are taking the expected value of a complicated function. If it's easy to generate random numbers from the distribution of x, you might want to try Monte Carlo integration rather than numerical integration.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.