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
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 "-".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With