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.kapetana...@gmail.com> 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 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. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.