Multiply permutations of two vectors in R

吃可爱长大的小学妹 提交于 2019-11-28 14:37:35

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)

Have a look at expand.grid or outer

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

We can try vapply:

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