Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using outer() with a multivariable function

Tags:

r

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?

like image 338
Stijn Avatar asked Aug 14 '12 11:08

Stijn


People also ask

How do you write a function with two variables?

A function of two variables z=(x,y) maps each ordered pair (x,y) in a subset D of the real plane IR2 to a unique real number z. The set D is called the domain of the function. The range of f is the set of all real numbers z that has at least one ordered pair (x,y)∈D such that f(x,y)=z as shown in Figure 13.1.

Can a function have 2 variables?

A function of two variables is a function, that is, to each input is associated exactly one output. The inputs are ordered pairs, (x,y). The outputs are real numbers (each output is a single real number).

What does the outer function do in R?

outer() function in R Programming Language is used to apply a function to two arrays. Parameters: x, y: arrays. FUN: function to use on the outer products, default value is multiply.


2 Answers

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))
like image 35
Brian Diggs Avatar answered Nov 16 '22 00:11

Brian Diggs


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.

like image 105
Backlin Avatar answered Nov 16 '22 01:11

Backlin