Skip to contents

row_sums() computes the sum 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]].

Usage

row_sums(.cols, na.rm = FALSE, .label = NULL, .description = NULL)

Arguments

.cols

<tidy-select> Columns to sum across, evaluated via dplyr::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). If TRUE, NA values are excluded before summing. If all values in a row are NA and na.rm = TRUE, the result is 0 (matching base R rowSums() behavior). Default FALSE.

.label

character(1) or NULL. Variable label stored in @metadata@variable_labels[[col]] after mutate(). If NULL, falls back to the output column name from dplyr::cur_column().

.description

character(1) or NULL. Plain-language description of the transformation stored in @metadata@transformations[[col]]$description after mutate().

Value

A double vector of length equal to the number of rows in the current data context.

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 total
mutate(d, total = row_sums(c(y1, y2)))
#> 
#> ── Survey Design ───────────────────────────────────────────────────────────────
#> <survey_taylor> (Taylor series linearization)
#> Sample size: 3
#> 
#> # A tibble: 3 × 4
#>      y1    y2    wt total
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     1     4     1     5
#> 2     2     5     1     7
#> 3     3     6     1     9

# use tidy-select for columns and add a label
d |>
  mutate(
    total = row_sums(
      tidyselect::starts_with("y"),
      na.rm = TRUE,
      .label = "Total"
    )
  )
#> 
#> ── Survey Design ───────────────────────────────────────────────────────────────
#> <survey_taylor> (Taylor series linearization)
#> Sample size: 3
#> 
#> # A tibble: 3 × 4
#>      y1    y2    wt total
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     1     4     1     5
#> 2     2     5     1     7
#> 3     3     6     1     9