Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform 'cross product' of two vectors, but with addition

I am trying to use R to perform an operation (ideally with similarly displayed output) such as

> x<-1:6
> y<-1:6
> x%o%y
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3    4    5    6
[2,]    2    4    6    8   10   12
[3,]    3    6    9   12   15   18
[4,]    4    8   12   16   20   24
[5,]    5   10   15   20   25   30
[6,]    6   12   18   24   30   36

where each entry is found through addition not multiplication.

I would also be interested in creating the 36 ordered pairs (1,1) , (1,2), etc...

Furthermore, I want to use another vector like

z<-1:4

to create all the ordered triplets possible between x, y, and z.

I am using R to look into likelihoods of possible total when rolling dice with varied numbers of sizes.

Thank you for all your help! This site has been a big help to me. I appreciate anyone that takes the time to answer a stranger's question.

UPDATE So I found that `outer(x,y,'+') will do what I wanted first. But I still don't know how to create ordered pairs or ordered triplets.

like image 456
Michael Avatar asked Jul 13 '11 19:07

Michael


2 Answers

expand.grid can answer your second question:

expand.grid(1:6,1:6)
expand.grid(1:6,1:6,1:4)
like image 35
Joshua Ulrich Avatar answered Nov 17 '22 21:11

Joshua Ulrich


Your first question is easily handled by outer:

outer(1:6,1:6,"+")

For the others, I suggest you try expand.grid, although there are specialized combination and permutation functions out there as well if you do a little searching.

like image 189
joran Avatar answered Nov 17 '22 22:11

joran