[R] How to integrate a function with additional argument being a vector or matrix?
jim holtman
jholtman at gmail.com
Wed Dec 22 14:18:23 CET 2010
Change as follows:
> integrand <- function(x, vec, mat, val) rep(1, length(x)) # 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)
[1] 1
> integrate(integrand, lower = 0, upper = 1, vec = u, mat = A, val = 4)
1 with absolute error < 0.000000000000011
>
Notice in the help page for integrate:
an R function taking a numeric first argument and returning a numeric
vector of the same length. Returning a non-finite element will
generate an error
Your function has to return a vector of the same length as 'x'
On Wed, Dec 22, 2010 at 7:43 AM, Marius Hofert <m_hofert at web.de> 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
>
> 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.
>
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
More information about the R-help
mailing list