I am trying to use trapezoid integration, and as a result integrating the survival function(1-F(x)) of a mixture of lognormal distribution, using the code below:
for(i in 1: nrow(mydf)){
mydf$Ex[i]<- trapzfun(function(x){(1-pnorm((log(x)-mydf$mu1[i])/mydf$sd1[i]))*mydf$pmix1[i]+(1-pnorm((log(x)-mydf$mu2[i])/mydf$sd2[i]))*mydf$pmix2[i]},a=0,b=1)
mu1
,sd1
,pmix1
is my mean,std in logscale. pmix1
and pmix2
are mixing proportions.
While this is running well, it is taking about 3-5 hours of run time. I guess "for loops" are not a good method, and I am pretty new to R. I did try to use an apply function:
mixture<- function(x){
trapzfun(function(x){(1-plnorm(x,mydf$mu1,mydf$sd1))*mydf$pmix1+(1-plnorm(x,mydf$mu2,mydf$sd2))*mydf$pmix2},a=0,b=1)
}
[Note the similarity with plnorm and pnorm using the transformation I applied]
mydf$Ex_1<- apply(mydf,1,mixture)
It is returning list(value = c(0.055257000747731, 0.055257000747731, 0.00.....
Can you please help me on this problem!