Applying function to cartesian product of two unequal vectors

506 views Asked by At

I am trying to avoid looping by using an documented apply function, but have not been able to find any examples to suit my purpose. I have two vectors, x which is (1 x p) and y which is (1 x q) and would like to feed the Cartesian product of their parameters into a function, here is a parsimonious example:

    require(kernlab)
    x = c("cranapple", "pear", "orange-aid", "mango", "kiwi", 
           "strawberry-kiwi", "fruit-punch", "pomegranate")
    y = c("apple", "cranberry", "orange", "peach")

    sk <- stringdot(type="boundrange", length = l, normalized=TRUE)
    sk_map = function(x, y){return(sk(x, y))}

I realize I could use an apply function over one dimension and loop for the other, but I feel like there has to be a way to do it in one step... any ideas?

2

There are 2 answers

4
eipi10 On BEST ANSWER

Is this what you had in mind:

sk <- stringdot(type="boundrange", length = 2, normalized=TRUE)

# Create data frame with every combination of x and y
dat = expand.grid(x=x,y=y)

# Apply sk by row
sk_map = apply(dat, 1, function(dat_row) sk(dat_row[1],dat_row[2]))
0
Greg Snow On

You can use the outer function for this if your function is vectorized, and you can use the Vectorize function to create a vectorized function if it is not.

outer(x,y,FUN=sk)

or

outer(x,y, FUN=Vectorize(sk))