Stijn
Stijn

Reputation: 551

Using outer() with a multivariable function

Suppose you have a function f<- function(x,y,z) { ... }. How would you go about passing a constant to one argument, but letting the other ones vary? In other words, I would like to do something like this:

 output <- outer(x,y,f(x,y,z=2)) 

This code doesn't evaluate, but is there a way to do this?

Upvotes: 16

Views: 5079

Answers (2)

Brian Diggs
Brian Diggs

Reputation: 58875

outer (along with the apply family of functions and others) will pass along extra arguments to the functions which they call. However, if you are dealing with a case where this is not supported (optim being one example), then you can use the more general approach of currying. To curry a function is to create a new function which has (some of) the variables fixed and therefore has fewer parameters.

library("functional")
output <- outer(x,y,Curry(f,z=2))

Upvotes: 2

Backlin
Backlin

Reputation: 14872

outer(x, y, f, z=2)

The arguments after the function are additional arguments to it, see ... in ?outer. This syntax is very common in R, the whole apply family works the same for instance.

Update:

I can't tell exactly what you want to accomplish in your follow up question, but think a solution on this form is probably what you should use.

outer(sigma_int, theta_int, function(s,t)
    dmvnorm(y, rep(0, n), y_mat(n, lambda, t, s)))

This calculates a variance matrix for each combination of the values in sigma_int and theta_int, uses that matrix to define a dennsity and evaluates it in the point(s) defined in y. I haven't been able to test it though since I don't know the types and dimensions of the variables involved.

Upvotes: 19

Related Questions