row_means() computes the mean of each row across a tidyselect-selected set
of numeric columns. It is designed for use inside mutate() on survey design
objects. When called inside mutate(), the transformation is recorded in
@metadata@transformations[[col]].
Arguments
- .cols
<
tidy-select> Columns to average across, evaluated viadplyr::pick(). Typical values:c(a, b, c),starts_with("y"),where(is.numeric). Must resolve to at least one column, and all selected columns must be numeric.- na.rm
logical(1). IfTRUE,NAvalues are excluded before computing the mean. If all values in a row areNAandna.rm = TRUE, the result isNaN(matching base RrowMeans()behavior). DefaultFALSE.- .label
character(1)orNULL. Variable label stored in@metadata@variable_labels[[col]]aftermutate(). IfNULL, falls back to the output column name fromdplyr::cur_column().- .description
character(1)orNULL. Plain-language description of the transformation stored in@metadata@transformations[[col]]$descriptionaftermutate().
See also
Other transformation:
make_binary(),
make_dicho(),
make_factor(),
make_flip(),
make_rev(),
row_sums()
Examples
# create a dummy survey object
d <- surveycore::as_survey(
data.frame(
y1 = c(1, 2, 3),
y2 = c(4, 5, 6),
wt = c(1, 1, 1)
),
weights = wt
)
# use a vector of columns to create the score
mutate(d, score = row_means(c(y1, y2)))
#>
#> ── Survey Design ───────────────────────────────────────────────────────────────
#> <survey_taylor> (Taylor series linearization)
#> Sample size: 3
#>
#> # A tibble: 3 × 4
#> y1 y2 wt score
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 4 1 2.5
#> 2 2 5 1 3.5
#> 3 3 6 1 4.5
# use tidy-select for columns and add a label
d |>
mutate(
score = row_means(
tidyselect::starts_with("y"),
na.rm = TRUE,
.label = "Score"
)
)
#>
#> ── Survey Design ───────────────────────────────────────────────────────────────
#> <survey_taylor> (Taylor series linearization)
#> Sample size: 3
#>
#> # A tibble: 3 × 4
#> y1 y2 wt score
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 4 1 2.5
#> 2 2 5 1 3.5
#> 3 3 6 1 4.5
