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]))
n=n+1
}
}
wy <- integrate(integral, 0, Inf)
print(wy)
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.
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.
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.