Search code examples
rlapplydo.callmahalanobis

mahalanobis distance for pair of columns in data frame in R


I have a dataframe table and I would like to calculate the mahalanobis for each possible pair of column of my dataframe.

           A1        A2          A3
     121.4984  219.5448    250.7575
     121.5195  219.5451    250.7500
     121.5089  219.4667    250.5645
     121.5510  219.6235    250.5645
     121.8034  219.4235    250.0005 

I would like to calculate the distance beetween A1 and A2, A1 and A3, A2 and A3 ... I may have up to 50 columns so If anyone has an idea how to do it :) Thanks


Solution

  • The function mahalanobis return the squared Mahalanobis distance, then you can do something like this:

    table <- iris[1:10, -5]
    coln <- combn(colnames(table), 2)
    out <- apply(coln, 2, function(x) sqrt(mahalanobis(table[, x], colMeans(table[, x]), cov(table[, x]))))
    colnames(out) <- apply(coln, 2, paste, collapse = "_")
    out
       Sepal.Length_Sepal.Width Sepal.Length_Petal.Length Sepal.Length_Petal.Width Sepal.Width_Petal.Length Sepal.Width_Petal.Width
    1                 0.6808740                 2.1111068                1.0495913                1.2242322               1.2236349
    2                 3.3019215                 0.4836711                0.1275204                1.0238329               1.3640406
    3                 0.3160289                 2.0549883                0.3040872                2.1087531               0.1284711
    4                 0.7972596                 2.3548714                0.8043597                1.3831695               0.5496880
    5                 1.0730825                 1.1132502                0.4512262                2.1350123               2.3749610
    6                 3.9962218                 5.6939205                6.3564033                6.0656020               5.4638846
    7                 3.4022539                 0.8045986                2.9231608                0.6036855               1.3184087
    8                 0.2499919                 0.2784879                0.4512262                0.2180897               0.4654446
    9                 2.5149505                 2.8599376                2.6288828                1.8544533               2.5715289
    10                1.6674153                 0.2451676                2.9035422                1.3831695               2.5399376
       Petal.Length_Petal.Width
    1                 0.2144860
    2                 0.2144860
    3                 2.2331776
    4                 0.5509346
    5                 0.2144860
    6                 6.9434579
    7                 2.3803738
    8                 0.5509346
    9                 0.2144860
    10                4.4831776