R/oggr.R

Defines functions make_wtvar makewt

Documented in makewt make_wtvar

#' Make weight variable
#'
#' This function calculates weights from unweighted distribution of a data frame variable
#' by checking against a target distribution reflecting the first variable. The resulting
#' weight variable is joined to original data frame.
#' @param data A data frame object
#' @param weightgroup The column containing the data used as base for weighting
#' @param proptargets A numeric vector specifying the proportions the weightgroup should display when the weighting variable is applied
#' @keywords makeweight mweight
#' @export
#' @examples
#' weighted_dat <- makewt(data = dat, weightgroup = "gender", proptargets = c(.5, .5))

makewt <- function(data, weightgroup, proptargets) {
    a <- data.frame(table(data[, weightgroup]))
    a <- data.frame(cbind(a[, 1], data.frame(w = (proptargets * sum(a[, 2]))/a[, 2])))
    names(a) <- c(weightgroup, "weight")
    b <- merge(data, a, by.x = weightgroup, by.y = 1, all.x = TRUE)
    return(b)
}


#' Make standalone weight variable
#'
#' This function calculates weights from unweighted distribution of a data frame variable
#' by checking against a target distribution reflecting the first variable. The results
#' are stored in separate data frame
#' @param data A data frame object
#' @param id The column in the data frame containing a unique key
#' @param weightgroup The column containing the data used as base for weighting
#' @param proptargets A numeric vector specifying the proportions the weightgroup should display when the weighting variable is applied
#' @keywords make_wtvar makeweight
#' @export
#' @examples
#' weighted_dat <- make_wtvar(data = dat, id = "id", weightgroup = "gender", proptargets = c(.5, .5))

make_wtvar <- function(data, id, weightgroup, proptargets) {
    a <- data.frame(table(data[, weightgroup]))
    a <- data.frame(cbind(a[, 1], data.frame(w = (proptargets * sum(a[, 2]))/a[, 2])))
    names(a) <- c(weightgroup, "weight")
    b <- merge(data, a, by.x = weightgroup, by.y = 1, all.x = TRUE)
    b <- b[, c(id, "weight")]
    b <- b[order(b[,1]) , ]
    return(b)
}

# dat <- data.frame(id = 1:100,
#                   gender = c(rep("Male", 42), rep("Female", 55), rep(NA, 3)))
ogsj/oggr documentation built on Sept. 16, 2017, 9:25 p.m.