File: sampleCat.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 (25 lines) | stat: -rw-r--r-- 720 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
25
#' Random aggregation function for a factor variable
#' 
#' The function sampleCat samples with probabilites corresponding to the
#' occurrence of the level in the NNs. 
#' 
#' @param x factor vector 
#' @param weights numeric vector providing weights for the observations in x
#' @family imputation methods
#' @export 


sampleCat <- function(x,weights = NULL){
  #sample with probabilites corresponding to there number in the NNs
  if(!is.factor(x))
    x <- as.factor(x)
  s <- summary(x)
  s <- s[s!=0]
  if(!is.null(weights)){
    tmpTab <- merge(aggregate(weights,list(x),sum), data.frame("Group.1"=names(s),prob=s))
    s <- tmpTab$prob*tmpTab$x
    names(s) <- tmpTab$Group.1
  }
  
  sample(names(s),1,prob=s)
}