我有两个长度为4的向量,想要对向量的排列进行乘法:
A=(a1,a2,a3,a4)
B=(b1,b2,b3,b4)
我想:
a1*b1;a1*b2;a1*b3...a4*b4
作为已知顺序的列表或row.names= a and colnames=B的data.frame
看看expand.grid
或outer
combination <- expand.grid(A, B)
combination$Result <- combination$A * combination$B
outer(A, B, FUN = "*")
使用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…用z
代替t(z)
)
我们可以试试vapply
:
vapply(B, '*', A, FUN.VALUE=numeric(length(A)))