Multiply permutations of two vectors in R

故事扮演 提交于 2019-11-27 19:39:15

问题


I've got two vectors of the length 4 and want a multiplication of the permutations of the vector:

A=(a1,a2,a3,a4)
B=(b1,b2,b3,b4)

I want:

a1*b1;a1*b2;a1*b3...a4*b4

as a list with known order or data.frame with row.names=A and colnames=B


回答1:


Use outer(A,B,'*') which will return a matrix

x<-c(1:4)
y<-c(10:14)
outer(x,y,'*')

returns

     [,1] [,2] [,3] [,4] [,5]
[1,]   10   11   12   13   14
[2,]   20   22   24   26   28
[3,]   30   33   36   39   42
[4,]   40   44   48   52   56

and if you want the result in a list you then can do

z<-outer(x,y,'*')
z.list<-as.list(t(z))

head(z.list) returns

[[1]]
[1] 10

[[2]]
[1] 11

[[3]]
[1] 12

[[4]]
[1] 13

[[5]]
[1] 14

[[6]]
[1] 20

which is x1*y1, x1*y2, x1* y3, x1*y4, x2*y1 ,... (if you want x1*y1, x2*y1, ... replace t(z) by z)




回答2:


Have a look at expand.grid or outer

combination <- expand.grid(A, B)
combination$Result <- combination$A * combination$B
outer(A, B, FUN = "*")



回答3:


We can try vapply:

vapply(B, '*', A, FUN.VALUE=numeric(length(A)))


来源:https://stackoverflow.com/questions/33282092/multiply-permutations-of-two-vectors-in-r

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