grp_freq
calculates the frequency and optionally the percentage of a variable
by groups in survey data, supporting weighted and unweighted data.
Usage
grp_freq(
data,
groups,
weight = NULL,
set_names = NULL,
addPercent = FALSE,
groupsPercent = NULL,
round_decimals = NULL
)
Arguments
- data
A data frame containing survey data.
- groups
A vector of variable names for grouping. This parameter is required and can include one or multiple variables.
- weight
An optional variable containing weight factors for the analysis.
- set_names
An optional vector of custom column names for the output data frame.
- addPercent
Logical; if
TRUE
, adds a percentage column based on the frequency. The default isFALSE
.- groupsPercent
An optional vector of variables for calculating percentages. If
NULL
, percentages are calculated for the total.- round_decimals
An optional numeric value specifying the number of decimal places to round numeric data. By default, no rounding is applied.
Details
The function groups data based on the specified variables and calculates frequencies. It can also calculate percentages, either overall or grouped by additional variables. The data can be optionally weighted, and the output can be customised with specific column names.
Examples
if (FALSE) { # \dontrun{
# Calculate unweighted frequencies by group with percent added
df <- grp_freq(dataset, groups = c("age_categories", "gender"), addPercent = TRUE)
# Calculate weighted frequencies by group with custom column names
df <- grp_freq(dataset, groups = c("age_categories", "gender"),
weight = "wgtvar", set_names = c("Age", "Gender", "n"))
} # }