简体   繁体   English

通过减去两个向量在 R 中创建一个矩阵

[英]Create a matrix in R from subtracting two vectors

I have two vectors and want to create a matrix in R, subtracting one from the other.我有两个向量,想在 R 中创建一个矩阵,从另一个中减去一个。

Vector1 <- c(1,2,3)
Vector2 <- c(2,3,4,5)

The resulting matrix then would have three columns and four rows.然后,生成的矩阵将具有三列和四行。 The matrix would be vector1 minus each sequential element of vector2.矩阵将为vector1减去vector2的每个顺序元素。 Eg the first row would be vector1 minus the first element of vector2 (ie, (1-2), (2-2), (3-2)).例如,第一行将是vector1 减去vector2 的第一个元素(即(1-2)、(2-2)、(3-2))。 The second row would be vector1 minus the second element of vector2 (ie (1-3),(2-3),(3-3)) and so on.第二行将是vector1 减去vector2 的第二个元素(即(1-3)、(2-3)、(3-3))等等。

In reality the vectors are much longer.实际上,向量要长得多。

You can use outer :您可以使用outer

outer(-Vector2, Vector1, "+")
#t(outer(Vector1, Vector2, "-")) #Alternative
#     [,1] [,2] [,3]
#[1,]   -1    0    1
#[2,]   -2   -1    0
#[3,]   -3   -2   -1
#[4,]   -4   -3   -2

How about this:这个怎么样:

t(sapply(Vector2, function(x) Vector1-x))
     [,1] [,2] [,3]
[1,]   -1    0    1
[2,]   -2   -1    0
[3,]   -3   -2   -1
[4,]   -4   -3   -2

You can create a matrix using matrix([elements], [number of rows], [number of columns]) .您可以使用matrix([elements], [number of rows], [number of columns])创建矩阵。 The elements of your matrix can be computed as Vector1 - rep(Vector2, length(Vector1)) , where rep repeats the elements of Vector2 a number of times equal to the length of 'Vector1`, so that you get all the differences you are looking for.矩阵的元素可以计算为Vector1 - rep(Vector2, length(Vector1)) ,其中rep重复Vector2的元素的次数等于“Vector1”的长度,这样你就得到了你的所有差异寻找。 Putting all of this together, we get:将所有这些放在一起,我们得到:

matrix(Vector1 - rep(Vector2, length(Vector1)), length(Vector2), length(Vector1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM