R中两个向量的乘法排列

时间:2015-10-22 13:22:41

标签: r permutation vector-multiplication

我有两个长度为4的向量,并希望对向量的乘法进行乘法运算:

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

我想:

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

作为已知订单的列表或具有row.names = A和colnames = B的data.frame

3 个答案:

答案 0 :(得分:3)

查看expand.gridouter

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

答案 1 :(得分:2)

使用outer(A,B,'*')将返回矩阵

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

返回

     [,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

如果你想在列表中得到结果,你可以做

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

head(z.list)返回

[[1]]
[1] 10

[[2]]
[1] 11

[[3]]
[1] 12

[[4]]
[1] 13

[[5]]
[1] 14

[[6]]
[1] 20

是x1 * y1,x1 * y2,x1 * y3,x1 * y4,x2 * y1,...(如果你想要x1 * y1,x2 * y1,...替换t(z) z

答案 2 :(得分:2)

我们可以尝试vapply

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