R/rdepth.R

rdepth <-
function(d, x, y, sortx = T)
{
##########################################################################
# This function computes the regression depth of a line with coordinates d
# relative to the bivariate data set (x,y).
# The first component of the vector d indicates the intercept of the line,
# the second component is the slope.
#
# Input : d          : vector with two components
#         x,y        : vectors of equal length (data set)
#         sortx      : logical, to set to F if the data set (x,y) is
#                      already sorted by its x-coordinates
#
# Reference:
#           Rousseeuw, P.J. and Hubert, M. (1996),
#           Regression Depth, Technical report, University of Antwerp
#           submitted for publication.
##########################################################################
        if(!is.vector(x) || !is.vector(y)) stop("x and y should be vectors")
        n <- length(x)
        if(n < 2)
                stop("you need at least two observations")
        xy <- cbind(x, y)
        b <- d[1]
        a <- d[2]
        if(sortx)
                xy <- xy[order(xy[, 1], xy[, 2]),  ]
        res <- xy[, 2] - a * xy[, 1] - b
        res[abs(res) < 9.9999999999999995e-08] <- 0
        posres <- res >= 0
        negres <- res <= 0
        lplus <- cumsum(posres)
        rplus <- lplus[n] - lplus
        lmin <- cumsum(negres)
        rmin <- lmin[n] - lmin
        depth <- pmin(lplus + rmin, rplus + lmin)
        min(depth)
}
musto101/wilcox_R documentation built on May 23, 2019, 10:52 a.m.