###### WEIGHTED MEDIANS ###### ### CONSTRUCTING THE "BIVARIATE SORTING" FUNCTION ### This function sorts "y" keeping the pairs (x_i,y_i) together my.sort = function(x,y) { mm = sort(y,index.return = T)$ix x = x[mm] y = y[mm] cbind(x,y) } ########################################################################## ########################################################################## ### FUNCTION TO FORM A DISTRIBUTION FUNCTION ### GIVEN A SET OF WEIGHTS F = function(y,x=rep(1,length(y))) { ## y: vector of dim "n". It can have repeated values. ## x: vector of dim "n". The weight of y[i] is proportional to abs(x_i) w = abs(x)/sum(abs(x)) re = my.sort(w,y) y = re[,2] w = re[,1] l_y = length(y) yy = unique(y) l_yy = length(yy); ww = rep(0,l_yy) i = 1 for(j in 1:l_yy) { while(y[i]==yy[j] & i <= l_y) { ww[j] = ww[j]+w[i] i = i+1 } } ww = cumsum(ww) re = cbind(yy,ww) re } ######################################################################### ######################################################################### ### FUNCTION TO COMPUTE THE "WEIGHTED MEDIAN" my.median = function(y,x=rep(1,length(y)),full = FALSE) { re = F(y,x) ## COMPUTING THE "LOWER" AND "UPPER" MEDIANS, AND THE MEDIAN test = which(re[,2]==1/2) if(length(test)==1) { med_low = re[test,1]; med_up = re[test+1,1] med = (med_low +med_up)/2 if(full == TRUE){ res = list("med_low" = med_low,"med_up"=med_up,"med"=med) } else { res = med } } if(length(test)<1) { i = 1 while( re[i,2] < 1/2) { ss = re[i,2] i = i+1 } med_low = med_up = med = re[i,1] if(full == TRUE){ res = list("med_low" = med_low,"med_up"=med_up,"med"=med) } else { res = med } } res res } my.median(y) my.median(y,x) ######################################################################### ############################# TESTING THE FUNCTIONS #################### ######################################################################### ### "BIVARIATE SORTING" FUNCTION set.seed(123) y = sample(1:10,replace = T) x = 1:length(y) cbind(x,y) my.sort(x,y) ### "CUMMULATIVE DISTRIBUTION" FUNCTION set.seed(123) y = sample(1:10,replace=T) x = rep(1,length(y)) cbind(x,y) # To see the data F(y,x) # To see the cummulative distribution set.seed(124) y = sample(1:10,replace=T) x = rep(1,length(y)) cbind(x,y) F(y,x) # To see the cummulative distribution ### "WEIGHTED MEDIAN" FUNCTION re = my.median(y,x,full = T) re median(y) set.seed(123) y = sample(1:15,replace=T) x = rep(1,length(y)) cbind(x,y) # To see the data F(y,x) # To see the cummulative distribution re = my.median(y,x) re median(y) set.seed(123) x = round(rnorm(length(y)),2) cbind(x,y) F(y,x) # To see the cummulative distribution re = my.median(y,x) re set.seed(123) y = sample(1:15,replace=T) x = rep(1,length(y)) cbind(x,y) # To see the data F(y,x) # To see the cummulative distribution re = my.median(y,x) re median(y) set.seed(123) y = sample(1:100,replace = T) x = 1:length(y) cbind(x,y) my.median(y,x)