R/wtd.median.r

Defines functions wtd.median

Documented in wtd.median

#' Find Median of Variable
#'
#' Makes use of the wtd.quantile function, part of the Hmisc package
#' @param x A variable
#' @param weights Sampling weights of variable (optional)
#' @return Returns the median value of the variable
#' @description Takes in variable and finds median, works with sampling weights
#' @examples 
#'    library(poliscidata)
#'    
#'    wtd.median(nes$budget_deficit_x, nes$wt)
#' @export
#' @importFrom Hmisc wtd.quantile

wtd.median = function(x, weights=NULL)
{
  result = Hmisc::wtd.quantile(as.numeric(x), weights, probs=.5)
  if(is.factor(x)) { return(levels(x)[result]) }
  if(!is.factor(x)) { return(as.numeric(result)) }   
}

Try the poliscidata package in your browser

Any scripts or data that you put into this service are public.

poliscidata documentation built on Oct. 19, 2018, 5:05 p.m.