17

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?

1
  • 1
    You know what, I realized I've often been doing this sort of thing with do.call(lapply, c(expand.grid(x, y), list(f))), but outer is definatelly better and more readable. Commented Aug 14, 2012 at 13:17

2 Answers 2

20
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.

Sign up to request clarification or add additional context in comments.

6 Comments

Ah it's so simple, I have much to learn about R I see... Thanks a lot!
Yes, it's simple... once you know it ;)
Sorry to bother you again, but what if I have a function which is dependent on another function? For instance, say I have two intervals, and for each two elements out of these intervals I want to (i) create an associated variance matrix and (ii) calculate the density at this point (a multivariate normal distribution). To create the variance matrix I have a function y_mat(n,lambda,theta,sigma). Given two intervals sigma_int and theta_int, I wanna do something like z <- outer(sigma_int,theta_int,dmvnorm,x=y,mean=rep(0,n),sigma=y_mat(n,lambda,theta,sigma)). Is this possible?
That's surely possible to do, but I'll have to get back to you later, cause I have to run an errand now.
I eagerly await your response.
|
2

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)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.