0
votes

I have two vectors and want to create a matrix in R, subtracting one from the other.

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. E.g. the first row would be vector1 minus the first element of vector2 (i.e., (1-2), (2-2), (3-2)). The second row would be vector1 minus the second element of vector2 (i.e. (1-3),(2-3),(3-3)) and so on.

In reality the vectors are much longer.

3

3 Answers

1
votes

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
1
votes

You can use 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
0
votes

You can create a matrix using 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. Putting all of this together, we get:

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