R/sample_logp.R

Defines functions sample_logp

Documented in sample_logp

#' Sample with unequal and unnormalized log-probabilities
#' 
#' Samples with replacement from given log-probability vector
#' 
#' @param x a vector of possible outcomes
#' @param size number of samples to take, where sampling is with replacement
#' @param lp_vec a numeric vector that contains the log-probabilities with which to sample. These probabilities might or not be normalized to sum to one.
#' @return a sample of size \code{size} from \code{x}
#' @examples
#' K = 4
#' 
#' # unnormalized probability vector (on log-scale)
#' lq_vec = log(runif(K))
#' 
#' # sample first K letters according to lqvec
#' x = sample_logp(letters[1:K], 1000, lq_vec)
#' @export
sample_logp = function(x, size, lp_vec) {
    
    # check arguments
    if (length(x) != length(lp_vec))
        stop("length of x and lp_vec do not match")
    if (size %% 1 != 0)
        stop("size has to be an integer value")

    # sample
    indx = .sample_index_logp(size, lp_vec) + 1L
    x[indx]
    
}
baruuum/btoolbox documentation built on Aug. 17, 2020, 1:29 a.m.