Search code examples
pythonrspotfiremedianweighted

Spotfire Weighted Median value


Is there any function which returns weighted Median value?

Input 2 columns like weight = [100,210,30,50] values = [1, 2, 3, 4]

and maybe function like WeightedMedian(w = weight, v = values)

or can you help me to construct code for that, Data-->Data Function Properties --> Expression Functions --> New.

or formula in Custom Expression


Solution

  • Weighted median is just the first value for which the cumsum of the weights divided by the total sum of all weights exceeds 0.5.

    WeightedMedian <- function(w, v) {
      
      # in case when v is not sorted 
      i <- order(v)
      v <- v[i]
      w <- w[i]
      
      v[which(cumsum(w) / sum(w) > 0.5)[1]]
      
    }
    
    WeightedMedian(w =  c(100, 210, 30, 50), v = c(1, 2, 3, 4))
    
    # [1] 2