Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R distance matrix build from two vectors (n,1)

Tags:

r

matrix

distance

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.

like image 584
Rami Dr Avatar asked Sep 05 '25 03:09

Rami Dr


2 Answers

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.

like image 98
CHP Avatar answered Sep 08 '25 01:09

CHP


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.

like image 38
Jilber Urbina Avatar answered Sep 08 '25 01:09

Jilber Urbina