Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing a difference matrix from a vector in R

Tags:

r

Say I have a vector:

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

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

So the equivalent of:

    11    21    32    55    
11   0    10    21    44
21  -10    0    11    34
32  -21  -11     0    23
55  -44  -34   -23     0
like image 750
user1172468 Avatar asked Jan 17 '26 06:01

user1172468


2 Answers

You can use outer() to do 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() computes an outer product on two vectors, with a custom function. Since the operator - is also a function, you can use it inside outer(). However, since - is a non-standard name, you have to use backticks or quotes, i.e. `-` or "-".

like image 76
Andrie Avatar answered Jan 19 '26 20:01

Andrie


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
like image 26
rcs Avatar answered Jan 19 '26 19:01

rcs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!