Learn R Programming

cwhmisc (version 2.1)

weighted.median: Weighted median

Description

Compute the sample median of the vector of values given as its first argument. The weights are given in the second argument; if given, must be of the same length as first argument.

Usage

weighted.median(x, w=NULL, na.rm=FALSE)

Arguments

x
a numeric vector containing the values whose median is to be computed.
w
a numeric vector containing the weights.
na.rm
a logical value indicating whether NA values should be stripped before the computation proceeds.

Value

  • Unweighted mean, if weights w are not given. Otherwise, value of x nearest to the position, where the cumulative sum of the weights reaches 50% of its maximum value.

    Special cases are considered as closely as possible, see code.

See Also

median, quantile

Examples

Run this code
weighted.median(c(7,1,2,4,10,15),c(1,1/3,1/3,1/3,1,1)) # 8.5 [even number]
weighted.median(c(1,2,4,7,10,15),c(1/3,1/3,1/3,1,1,1)) # ordered differently  8.5
weighted.median(c(7,7/3,10,15)) # same as previous, but unweighted:
         # '1','2','4 of weights='1/3' are replaced by '7/3' (weight=1)

weighted.median(c(7,1,2,4,10),c(1,1/3,1/3,1/3,1)) #  7
weighted.median(c(7,1,2,4,10)) #  4
weighted.median(c(7,1,NA,4,10),c(1,1/3,1/3,1/3,1),na.rm =TRUE) # 8.5}
<keyword>distribution</keyword>

Run the code above in your browser using DataLab