File: medianSamp.R

package info (click to toggle)
r-cran-vim 6.2.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,556 kB
  • sloc: cpp: 141; sh: 12; makefile: 2
file content (24 lines) | stat: -rw-r--r-- 603 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#' Aggregation function for a ordinal variable
#'
#' The function medianSamp chooses the level as the median or randomly between
#' two levels.
#'
#' @param x ordered factor vector
#' @param weights numeric vector providing weights for the observations in x
#' @family imputation methods
#' @export


medianSamp <- function(x,weights = NULL){
  if(length(x)==1){
    return(x)
  }
  if(is.null(weights)){
    m <- median(as.numeric(x))
  }else{
    m <- weightedMedian(as.numeric(x), weights = weights)
  }
  mi <- floor(m)
  
  return(levels(x)[mi+sample(c(0,1), size = 1, prob = c(1-(m-mi),m-mi))])
}