rcross-join

How to do cross join in R?


How can I achieve a cross join in R ? I know that "merge" can do inner join, outer join. But I do not know how to achieve a cross join in R.

Thanks


Solution

  • Is it just all=TRUE?

    x<-data.frame(id1=c("a","b","c"),vals1=1:3)
    y<-data.frame(id2=c("d","e","f"),vals2=4:6)
    merge(x,y,all=TRUE)
    

    From documentation of merge:

    If by or both by.x and by.y are of length 0 (a length zero vector or NULL), the result, r, is the Cartesian product of x and y, i.e., dim(r) = c(nrow(x)*nrow(y), ncol(x) + ncol(y)).