# [R] Integrate and mapply

Joshua Wiley jwiley.psych at gmail.com
Sun Nov 7 17:46:58 CET 2010

```Hi,

Have you tried just your function (undint) on its own (i.e., without
trying to feed it to integrate)?  If you did, you would notice that it
does not return anything (hence, "I could not get any result").  See

On Sun, Nov 7, 2010 at 8:01 AM, Vaiva P <asvaiva at gmail.com> wrote:
> Hi,
>
> I need some help on integrating a function that is a vector.
> I have a function - vector which each element is different. And,
> naturally, function integrate() does not work
> I checked the article of U. Ligges and J. Fox (2008) about code
> optimization "How Can I Avoid This Loop or Make It Faster?" on
> http://promberger.info/files/rnews-vectorvsloops2008.pdf.
> Their advice did not help me, because they advised a solution, when
> function was the same, but limits of the integral were  vectors. I
> have got everything other way around. I could not get any result.
> I would be very grateful for an advice on this matter.
> The code is below. The function needed to be integrated (undint with
> respect to u from 0 to Inf).
>
> Sincerely,
> V.
>
> Code
>
> rm=list(ls())

?

>
> #index matrix
> t1<-c(1:15)
> t2<-c(1:5)%x%matrix(1,3,1)
> t3<-matrix(1,3,1)%x%c(1:5)
> t4<-c(1:3)%x%matrix(1,5,1)
> comb<-cbind(t1,t2,t3,t4)
>
> nu<-rchisq(15,4)
>
> gam<-matrix(rchisq(75,df=5),15,5)
>
> undint<-function(u){
> prob<-function(i) {
> i1<-comb[i,1]
> i2<-comb[i,2]
> i3<-comb[i,3]
> i4<-comb[i,4]
>
> val1<-gam[((i3-1)*2+1):(i3*2),i4]
> vc1<-matrix(12,length(val1),1)-matrix(u,length(val1),1)-val1

this can be simplified to:  vc1 <- (12 - u) - val1

> distr1<-prod(pchisq(vc1,df=2))
>
> p10<-distr1*1/(exp(-nu[i1])*(1+gam[i2,i4]))*(1-plogis((u+log(gam[i3,i4])-log(1+gam[i2,i4])),0,1))
> p10
> }
> val<-c(1:15)

rather than assigning 1:15, just do (also consider a different name
than q because it is also the function to quit R):

q <- sapply(1:15, prob)

> q<-sapply(val,prob)

will at least let your function give you some output, but how do you
integrate from 0 to Inf when your function returns 15 numbers for
every 1 that goes in? sum(q)?

Best regards,

Josh

> }
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/

```