我在R中有两个向量:
a = seq(100, 10000, by=100)
b = c(0.05, 0.01, 0.005, 0.001)
如何创建一个看起来像
的4 x 100矩阵 a1*b1 a1*b2 ... a1*bn
a2*b1 a2*b2 ... a2*bn
等? a和b的大小/组件可能会发生变化,因此我需要一种通用的方法来执行此操作。
答案 0 :(得分:2)
我猜你正在寻找
outer(a, b, "*")
# [,1] [,2] [,3] [,4]
#[1,] 5 1 0.5 0.1
#[2,] 10 2 1.0 0.2
#[3,] 15 3 1.5 0.3
#[4,] 20 4 2.0 0.4
#[5,] 25 5 2.5 0.5
#[6,] 30 6 3.0 0.6
#[7,] 35 7 3.5 0.7
#[8,] 40 8 4.0 0.8
#[9,] 45 9 4.5 0.9
#[10,] 50 10 5.0 1.0
#...
或其转置
t(outer(a, b, "*"))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#[1,] 5.0 10.0 15.0 20.0 25.0 30.0 35.0 40.0 45.0 50 55.0 60.0 65.0 70.0
#[2,] 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11.0 12.0 13.0 14.0
#[3,] 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5 5.5 6.0 6.5 7.0
#[4,] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4
# [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26]
#[1,] 75.0 80.0 85.0 90.0 95.0 100 105.0 110.0 115.0 120.0 125.0 130.0
#[2,] 15.0 16.0 17.0 18.0 19.0 20 21.0 22.0 23.0 24.0 25.0 26.0
#[3,] 7.5 8.0 8.5 9.0 9.5 10 10.5 11.0 11.5 12.0 12.5 13.0
#[4,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6
#...