Learn R Programming

complexlm (version 1.1.2)

median.complex: Improved Median for Complex Numbers

Description

By default stats::median handles complex numbers by computing the medians of the real and imaginary components separately. This is not ideal as the result is not rotationally invariant (the same set of numbers will have a different median if the coordinates are rotated). This method calculates the complex median as the geometric median, as implemented in pracma::geo_median, which is rotationally invariant.

Usage

# S3 method for complex
median(x, na.rm = FALSE, tol = 1e-07, maxiter = 200, ...)

Value

The median of x. If x is complex, the geometric median as calculated by Weiszfeld's algorithm.

Arguments

x

a numeric or complex vector, of which the median is to be calculated.

na.rm

logical. Should NA values be removed before finding the median?

tol

numeric. Relative tolerance to be passed to pracma::geo_median. Default is 1e-07.

maxiter

maximum number of iterations for calculating geometric median. Not used if x is numeric.

...

Additional arguments. Currently ignored.

Details

The geometric median fails if any of the input data are colinear. Meaning that a straight line on the complex plane can be drawn which intersects with one or more element of x. If this function encounters such an error, it adds a small amount of random jitter to the data, then calculates the geometric medium again. The jitter is generated by a normal distribution with a standard deviation equal to the absolute minimum real or imaginary component of x, divided by \(10^8\) (or 10^-9 if the minimum is zero).

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

stats::median and pracma::geo_median

Examples

Run this code
set.seed(4242)
n <- 7
foo <- complex(real = rnorm(n), imaginary = rnorm(n))
median(foo)

Run the code above in your browser using DataLab