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

我只是一个虾纸丫 提交于 2019-12-19 21:59:24

问题


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.


回答1:


expand.grid can answer your second question:

expand.grid(1:6,1:6)
expand.grid(1:6,1:6,1:4)



回答2:


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.



来源:https://stackoverflow.com/questions/6684524/perform-cross-product-of-two-vectors-but-with-addition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!