[R] How to apply a two-place function to each combination of elements in two vectors of different lengths?

Marius Hofert m_hofert at web.de
Sat Jan 29 08:59:44 CET 2011


Dear expeRts,

I somehow can't manage to do the following:
Given two vectors x and y of lengths 3 and 2, respectively, I would like to apply 
a function to each combination of the entries of x and y and receive a 3-by-2 matrix
containing the results. Now outer() seems to be the way to go, but outer() expands
the vectors first, which leads to errors in my function. Here is the minimal example:

x <- c(5,6,7)
y <- c(2,4)

FUN <- function(x., y.){
    j <- 1:y.
    sum(choose(y., j)*choose(0.5*j, x.))
}
apply(expand.grid(x, y), 1, FUN=FUN) # that should give at least a vector of length 6, but also fails
outer(x, y, FUN=FUN) # hmm... I thought/hoped that worked... 

This should be easy but I just don't see it... :-(

Cheers,

Marius


More information about the R-help mailing list