stringrkernelapplykernlab

Applying function to cartesian product of two unequal vectors


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?


Solution

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