# We compare the implemented algorithm against a naive brute-force approach.
bruteForceTS <- function(x, y) {
n <- length(x)
medind1 <- floor(((n * (n - 1)) / 2 + 2) / 2)
medind2 <- floor((n + 2) / 2)
temp <- t(sapply(1:n, function(z) apply(cbind(x, y), 1 ,
function(k) (k[2] - y[z]) /
(k[1] - x[z]))))
TSslope <- sort(as.vector(temp[lower.tri(temp)]))[medind1]
TSintercept <- sort(y - x * TSslope)[medind2]
return(list(intercept = TSintercept, slope = TSslope))
}
n = 100
set.seed(2)
x = rnorm(n)
y = x + rnorm(n)
t0 <- proc.time()
TS.fast <- TheilSen(x, y, NULL, FALSE)
t1 <- proc.time()
t1 - t0
t0 <- proc.time()
TS.naive <- bruteForceTS(x, y)
t1 <- proc.time()
t1 - t0
TS.fast$slope - TS.naive$slope
Run the code above in your browser using DataLab