2

I am using pracma::integral2 to integrate a function that sometimes requires additional parameters, but integral2 seems not to recognise the parameters I supply. Consider these two functions:

fun1 <- function(x, y) exp(-x^2 - y^2)
fun2 <- function(x, y, a) (1 / a) * exp(-x^2 - y^2)

If I then run

integral2(fun1,
      xmin = 0,
      xmax = 1,
      ymin = 0,
      ymax = 1)$Q

I get 0.5577463 as expected. But if I run:

   integral2(fun2,
          xmin = 0,
          xmax = 1,
          ymin = 0,
          ymax = 1,
          a = 1)$Q

I get:

Error in fun(x, y, ...) : argument "a" is missing, with no default 

Trackback shows the following:

  1. fun(x, y, ...)
  2. FUN(X, Y)
  3. .tensor(xmin, xmax, thetaL, thetaR, phiB, phiT, FUN, phiBvar, phiTvar, vectorized = vectorized, singular = singular)
  4. integral2(fun2, xmin = 0, xmax = 1, ymin = 0, ymax = 1, a = 1)

I don't know what .tensor is, but it looks as if its product FUN(X,Y) has lost the ....

What is going wrong here?

JeremyC
  • 445
  • 2
  • 14

1 Answers1

3

a is being matched to the abstol argument of integral2. Just rename a to something else in fun2 as in solution 1 below or else specify abstol explicitly so it does not get confused as in solution 2 below.

library(pracma)

# solution 1
fun2aa <- function(x, y, aa) (1 / aa) * exp(-x^2 - y^2)
integral2(fun2aa,
          xmin = 0,
          xmax = 1,
          ymin = 0,
          ymax = 1,
          aa = 1)$Q
## [1] 0.5577463

# solution 2
fun2 <- function(x, y, a) (1 / a) * exp(-x^2 - y^2) # same as in question
integral2(fun2,
          xmin = 0,
          xmax = 1,
          ymin = 0,
          ymax = 1,
          abstol = 0, # added
          a = 1)$Q
## [1] 0.5577463

Note that if integral2 had put the dot dot dot before abstol then it would not have been a problem. Here integral2a is the same as integral2 except the dot dot dot is placed after ymax.

# solution 3

fun2 <- function(x, y, a) (1 / a) * exp(-x^2 - y^2) # same as in question

integral2a <- function (fun, xmin, xmax, ymin, ymax, ..., 
  sector = FALSE, reltol = 1e-06, abstol = 0, maxlist = 5000, 
  singular = FALSE, vectorized = TRUE) {}
body(integral2a) <- body(integral2)
environment(integral2a) <- environment(integral2)

integral2a(fun2,
          xmin = 0,
          xmax = 1,
          ymin = 0,
          ymax = 1,
          a = 1)$Q
## [1] 0.5577463
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Is there not a message here to anyone who writes functions in R packages? Most users do not want to check through a long list of default variables so that their own ... variables do not share an initial letter with that list. It destroys the whole idea of defaults. – JeremyC Oct 06 '18 at 20:24
  • Yes, the message is to put such arguments *after* the dot, dot, dot rather than before when writing the package. – G. Grothendieck Oct 06 '18 at 22:09