Skip to content
Prev 313195 / 398506 Next

Vectorizing integrate()

David et al

Thanks, I should have made the post more complete. I routinely use apply functions, but often avoid mapply() as I find it so non-intuitive. In this instance, I think the situation demands I change that position, though.

Reproducible code for the current implementation of the function is

B <- c(0,1)
sem1 = runif(10, 1, 2)
x <- rnorm(10)
X <- cbind(1, x)
eta <- numeric(10)

for(j in 1:nrow(X)){
	fun <- function(u) 1/ (1 + exp(- (B[1] + B[2] * (x[j] + u)))) * dnorm(u, 0, sem1[j])
	eta[j] <- integrate(fun, -Inf, Inf)$value
}

I can't get my head around how mapply() would work here. It accepts as its first argument a function. But, in my case I have two functions: the user defined integrand, fun(), an then of course calling the R function integrate().

I was thinking maybe along these lines, but this is obviously wrong.

mapply(integrate(function(u) 1/ (1 + exp(- (B[1] + B[2] * (x + u)))) * dnorm(u, 0, sem1), -Inf, Inf)$value, MoreArgs = list(B, x, sem1))