[R] How to integrate a function with additional argument beingavector or matrix?

Gerrit Eichner Gerrit.Eichner at math.uni-giessen.de
Wed Dec 22 14:16:29 CET 2010


On Wed, 22 Dec 2010, Marius Hofert wrote:

> Dear expeRts,
>
> I somehow don't see why the following does not work:
>
> integrand <- function(x, vec, mat, val) 1 # dummy return value
> A <- matrix(runif(16), ncol = 4)
> u <- c(0.4, 0.1, 0.2, 0.3)
> integrand(0.3, u, A, 4)
> integrate(integrand, lower = 0, upper = 1, vec = u, mat = A, val = 4)
>
> I would like to integrate a function ("integrand") which gets an "x" value (the running variable), a vector ("vec"), a matrix ("mat"), and a value ("val"). This function returns a number (set to 1 here). Of course, pointwise evaluation works without flaws. But why does integration not work? I obtain:
>
> Error in integrate(integrand, lower = 0, upper = 1, vec = u, mat = A,  :
>  evaluation of function gave a result of wrong length

Because your function isn't vectorized, i.e., does not *return* a vector. 
Instead,


integrand <- function(x, vec, mat, val) rep( 1, length( x)) # dummy return value


should work.

Hth  --  Gerrit

>
> Cheers,
>
> Marius
>
> ______________________________________________
> R-help at 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.



More information about the R-help mailing list