Skip to content

integrate (error: evaluation of function gave a result of wrong length)

3 messages · Dimitris.Kapetanakis, R. Michael Weylandt, Uwe Ligges

#
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 addition: Warning message:
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?

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.
#
Integrate works on functions that are vectorized (i.e., the algorithm
puts in N inputs and expects N outputs) -- your function is not
vectorized (and I'm not sure what integrating it means, but I'm not
looking too closely) but you can make it "look vectorized" with the
Vectorize() HOF. Note that this isn't magic (it's still actually a
loop) but it will help here.

Michael

On Wed, Feb 15, 2012 at 11:33 AM, Dimitris.Kapetanakis
<dimitrios.kapetanakis at gmail.com> wrote:
#
On 15.02.2012 17:33, Dimitris.Kapetanakis wrote:
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