# [R] integrate (error: evaluation of function gave a result of wrong length)

Uwe Ligges ligges at statistik.tu-dortmund.de
Wed Feb 15 18:06:48 CET 2012

```
On 15.02.2012 17:33, Dimitris.Kapetanakis wrote:
> Dear all,
>
> I am trying to use the integrate function in R but it seems that it does not
> work in my example and I cannot figure out why. I create a function Mu1
> (which works fine) and try to integrate by the code:
>
> n		<- 100
> Ctrl	<- as.matrix(cbind(runif(n, -30, 30)))
> W		<- Ctrl + as.matrix(rnorm(n))
> Rsp		<- (W>as.matrix(sample(10, n, T)))*1
>
> Mu1	<- function(x, Y=Rsp, Xc=Ctrl){
> 	x<- as.matrix(x)
> 	k<- dnorm((Xc-matrix(x, n, ncol(Xc), T)))
> 	K<- diag(apply(k, 1, function(c) prod(c)))
> 	delta<- solve(t(Xc)%*%K%*%Xc)%*%t(Xc)%*%K%*%Y
> 	delta[1]
> }
> Mu1(10)
> integrate(Mu1, -30, 30)
>
> then it posts me an error:
>
> Error in integrate(Mu1, -30, 30) :
>    evaluation of function gave a result of wrong length
> In matrix(x, n, ncol(Xc), T) :
>    data length [21] is not a sub-multiple or multiple of the number of rows
> [100]
>
> Could you please tell me where is the error and how I could correct it?

Mu1b <- Vectorize(Mu1, "x")
integrate(Mu1b, -30, 30)

Reason is that integrate passes multiple "x" into Mu1 at the same time,
hence that function has to be vectorized in x.

Uwe Ligges

> Thanks a lot
>
> Dimitris
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/integrate-error-evaluation-of-function-gave-a-result-of-wrong-length-tp4391036p4391036.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help