Skip to content

grp_mean calculates the mean (either unweighted or weighted) of a specified variable, grouped by one or more variables in survey data.

Usage

grp_mean(
  data,
  meanVar,
  groups,
  weight = NULL,
  set_names = NULL,
  round_decimals = NULL
)

Arguments

data

A data frame containing survey data.

meanVar

The variable for which the mean is to be calculated; must be numeric.

groups

Variables used for grouping; one or many variables can be specified.

weight

An optional variable containing weight factors for calculating the weighted mean.

set_names

An optional vector of custom column names for the output data frame.

round_decimals

An optional numeric value specifying the number of decimal places for rounding the mean values.

Value

A data frame containing the calculated means for each group, with the option to include weighted means and custom column names.

Details

The function can calculate either an unweighted mean if weight is NULL, or a weighted mean if weight is provided. If weight is provided, it calculates a weighted mean, accounting for the interaction between group variables. The function is designed to work with group interactions split by a full stop (.), which might affect the handling of group values containing periods. The results can be rounded to a specified number of decimal places, and custom column names can be set for the output data frame.

Examples

if (FALSE) { # \dontrun{
  # Calculate unweighted mean of 'age' grouped by 'gender'
  df <- grp_mean(dataset, meanVar = "age", groups = "gender")

  # Calculate weighted mean of 'age' grouped by 'gender', with custom column names
  df <- grp_mean(dataset, meanVar = "age", groups = "gender",
                 weight = "wgtvar", set_names = c("Gender", "Average Age"))
} # }