Anastasia
Anastasia

Reputation: 105

Calculate Euclidian distances between elements of two data sets

I have two data sets of the same size:

>df1

    c  d  e
a   2  3  4
b   5  1  3

>df2

   h  i  j
f  1  1  2
g  0  4  3

I need to calculate Euclidian distances between the same elements of these data sets to get:

   c  d  e
a  1  2  2
b  5  3  0

I have tried using dist(rbind(df1, df2)), but the result gave only one entry.

I have to perform this operation with numerous data sets, that's why your help will be really appreciated.

Upvotes: 0

Views: 43

Answers (2)

www
www

Reputation: 39154

The following will work if the data frames are all numeric and have the same column and row numbers.

df3 <- abs(df1 - df2)
df3
#   c d e
# a 1 2 2
# b 5 3 0

DATA

df1 <- read.table(text = "    c  d  e
a   2  3  4
                  b   5  4  3",
                  header = TRUE, stringsAsFactors = FALSE, row.names = 1)

df2 <- read.table(text = "    h  i  j
f  1  1  2
                  g  0  1  3",
                  header = TRUE, stringsAsFactors = FALSE, row.names = 1)

Upvotes: 2

rg255
rg255

Reputation: 4169

Given your update the solution would be to do absolute value (abs) of the difference:

abs(df1 - df2)

And you could make a function if you want to repeat the process a lot:

myfunc1 <- function(x1,x2){
  abs(x1 - x2)
}
myfunc1(df1, df2)

The output looks as intended:

     [,1] [,2] [,3]
[1,]    1    2    2
[2,]    5    3    0

Upvotes: 1

Related Questions