I have two vectors : x (n,1)
and y (n,1)
of real values, and I want to create a matrix M (n,n)
from these vectors which contains the distance between each two pairs.
You can use outer
function
x <- sample(5)
y <- sample(5)
x
## [1] 1 5 3 4 2
y
## [1] 2 3 5 1 4
outer(x, y, "-")
## [,1] [,2] [,3] [,4] [,5]
## [1,] -1 -2 -4 0 -3
## [2,] 3 2 0 4 1
## [3,] 1 0 -2 2 -1
## [4,] 2 1 -1 3 0
## [5,] 0 -1 -3 1 -2
You can replace "-"
with any other FUN which can take 2 vectors.
Take a look at ?dist
which:
computes and returns the distance matrix computed by using the specified distance measure to compute the distances between the rows of a data matrix.
Example:
> set.seed(1) # to make it reproducible
> dat <- data.frame(x = sample(5), y = sample(5)) # sample values
# calculating the distance between each row
> transform(dat, distance=apply(dat, 1, dist))
x y distance
1 2 5 3
2 5 4 1
3 4 2 2
4 3 3 0
5 1 1 0
Pay carefully attention to method
which provides with several methods to compute distance matrix.
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