Calculation of a difference matrix from a vector in R

Let's say I have a vector:

v <- c(11, 21, 32, 55)

Now I want to compute a diffmat matrix that contains the differences between all v elements

So the equivalent is:

    11    21    32    55    
11   0    10    21    44
21  -10    0    11    34
32  -21  -11     0    23
55  -44  -34   -23     0
+2
source share
2 answers

You can use outer()for this.

Try:

v <- c(11, 21, 32, 55)
outer(v, v, `-`)

     [,1] [,2] [,3] [,4]
[1,]    0  -10  -21  -44
[2,]   10    0  -11  -34
[3,]   21   11    0  -23
[4,]   44   34   23    0

The function outer()calculates the outer product on two vectors with a user-defined function. Since the operator is -also a function, you can use it internally outer(). However, since it -is a non-standard name, you must use return outputs or quotation marks, i.e. `-`or "-".

+5
source

You can use outer:

R> -outer(v, v, "-")
     [,1] [,2] [,3] [,4]
[1,]    0   10   21   44
[2,]  -10    0   11   34
[3,]  -21  -11    0   23
[4,]  -44  -34  -23    0
+4
source

Source: https://habr.com/ru/post/1692664/


All Articles