Iterate over cartesian product of vectors

后端 未结 2 706
感情败类
感情败类 2021-01-02 22:18

I have the following nested loop:

for (x in xs) {
    for (y in ys) {
        # Do something with x and y
    }
}

Which I’d like to flatten

2条回答
  •  礼貌的吻别
    2021-01-02 22:48

    R has a different paradigm than Python, so don't expect it to have generators or tuples -- we have vectors and indices for that.

    This way, to map a function on a Cartesian product simply call

    outer(xs,ys,function(x,y) ...)
    

    and undim the result if you wish.

    EDIT: In case xs or ys are something more complex than base vectors, one option is to use indices, i.e.

    outer(seq(a=xs),seq(a=ys),function(xi,yi) ... xs[[xi]]/ys[xi,]/etc. ...)
    

    or map a function on a bit hand-crafted product using mapply

    mapply(function(x,y) ...,xs,rep(ys,each=length(xs)))
    

提交回复
热议问题