elflyao
elflyao

Reputation: 387

How to do set multiplication(Cartesian product) in R

I know vectors can represent n-tuples and a list of vectors can represent a set of n-tuples. An easy algorithm would be

AxB<-list();k<-1L
for(i in seq_along(A))for(j in seq_along(B)){AxB[[k]]<-c(A[[i]],B[[j]]);k<-k+1L}
Are there more elegant data structures and algorithms to accomplish this?

Upvotes: 2

Views: 3101

Answers (2)

akrun
akrun

Reputation: 887501

We can use CJ from data.table

library(data.table)
CJ(a, b)

data

a <- c(1,2,6,3)
b <- c("a", "b", "c") 

Upvotes: 1

sanyi14ka
sanyi14ka

Reputation: 829

Giva a try to expand.grid function:

a<-list(1,2,6,3)
b<-list("a", "b", "c")
expand.grid(a,b)

Your output will be:

   Var1 Var2
1     1    a
2     2    a
3     6    a
4     3    a
5     1    b
6     2    b
7     6    b
8     3    b
9     1    c
10    2    c
11    6    c
12    3    c

And also look at the outer function. But in this case your variables have to be a vector or array.

Upvotes: 5

Related Questions