Skip to content

col_mean using survey::svymean #32

@kinto-b

Description

@kinto-b

If we use survey then we can support doing means for stratified samples. We'll want to keep the same API so something like

As a starting point, here's a rough function for doing cross tabs,

xtable <- function(.data, .row, .cols, .strata, .weight) {
  .data <- .data[!.data[[.row]] %in% NA, ] # Drop NA
  
  # Add binary variables for each level
  .rows <- c()
  for (val in unique(.data$a6)) {
    new_var <- paste0(".", .row, "__", val)
    .rows <- c(.rows, new_var)
    
    .data[[new_var]] <- .data[[.row]] %in% val
  }
  
  .design <- survey::svydesign(
    id = ~ 1, 
    strata = as.formula(paste("~", .strata)), 
    weights = as.formula(paste("~", .weight)), 
    data = .data
  )
  
  res <- survey::svyby(
    as.formula(paste("~", paste(.rows, collapse = "+"))), 
    as.formula(paste("~", paste(.cols, collapse = "+"))), 
    design = .design, 
    survey::svymean
  )
  
  # Only need TRUE cols
  res <- res[, !grepl(x=names(res), "FALSE$")]
  names(res) <- gsub(x=names(res), "TRUE$", "")
  
  t(res)
}

dat <- haven::read_sav("Z:/Reference information/CRSTabs/Example Data (SoCo ADA 16-17).sav")
xtable(dat, "a6", "year", "market", "wt_national")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions