Last data update: 2014.03.03

R: Calculate an n-by-n matrix by applying a function to all...
dist2R Documentation

Calculate an n-by-n matrix by applying a function to all pairs of columns of an m-by-n matrix.

Description

Calculate an n-by-n matrix by applying a function to all pairs of columns of an m-by-n matrix.

Usage

  dist2(x, fun, diagonal=0)

Arguments

x

A matrix.

fun

A symmetric function of two arguments that may be columns of x.

diagonal

The value to be used for the diagonal elements of the resulting matrix.

Details

With the default value of fun, this function calculates for each pair of columns of x the mean of the absolute values of their differences (which is proportional to the L1-norm of their difference). This is a distance metric.

The implementation assumes that fun(x[,i], x[,j]) can be evaluated for all pairs of i and j (see examples), and that fun is symmetric, i.e. fun(a, b) = fun(b, a). fun(a, a) is not actually evaluated, instead the value of diagonal is used to fill the diagonal elements of the returned matrix.

Note that dist computes distances between rows of x, while this function computes relations between columns of x (see examples).

Value

A symmetric matrix of size n x n.

Author(s)

Wolfgang Huber, James Reid

Examples


  # example matrix
  z = matrix(1:15693, ncol=3)
  matL1 = dist2(z)
  matL2 = dist2(z, fun=function(a,b) sqrt(sum((a-b)^2, na.rm=TRUE)))

  euc = as.matrix(dist(t(z)))

  stopifnot(identical(dim(matL2), dim(euc)),
            all(euc==matL2))

Results


R version 3.3.1 (2016-06-21) -- "Bug in Your Hair"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> library(genefilter)
> png(filename="/home/ddbj/snapshot/RGM3/R_BC/result/genefilter/dist2.Rd_%03d_medium.png", width=480, height=480)
> ### Name: dist2
> ### Title: Calculate an n-by-n matrix by applying a function to all pairs
> ###   of columns of an m-by-n matrix.
> ### Aliases: dist2
> ### Keywords: manip
> 
> ### ** Examples
> 
> 
>   # example matrix
>   z = matrix(1:15693, ncol=3)
>   matL1 = dist2(z)
>   matL2 = dist2(z, fun=function(a,b) sqrt(sum((a-b)^2, na.rm=TRUE)))
> 
>   euc = as.matrix(dist(t(z)))
> 
>   stopifnot(identical(dim(matL2), dim(euc)),
+             all(euc==matL2))
> 
> 
> 
> 
> 
> 
> dev.off()
null device 
          1 
>