egenvar: Extended variable generation

View source: R/egenvar.R

egenvarR Documentation

Extended variable generation

Description

Creates row-wise, group-wise, ranking, standardization, and identifier variables using a compact syntax inspired by Stata's egen, while following the active-data conventions of genvar().

Usage

egenvar(..., data = NULL, by = NULL, label = NULL, values = NULL)

Arguments

...

Named expressions in the form ⁠new_variable = function(...)⁠. An explicit data frame may also be supplied first for compatibility with other R4VN data-editing commands.

data

Optional explicit data frame. When omitted, the active data frame selected by usedf() is used.

by

Optional grouping variables, for example by = sex or by = vars(site, sex). Group summaries are repeated on every observation in the corresponding group.

label

Optional variable label or one label per generated variable.

values

Optional named value labels applied to generated variables.

Details

Row-wise functions accept individual variables, variable ranges, vars() selections, and wildcard selectors: rowmin(), rowmax(), rowmean(), rowsum(), rowmedian(), rowsd(), rowmiss(), rownonmiss(), rowfirst(), and rowlast(). Thus rowmean(q1:q10) is valid R4VN syntax.

Group/overall functions are mean(), sd(), min(), max(), median(), total(), count(), n(), seq(), z(), pctile(), and rank(). Without by, they operate over the complete data set. With by, they operate separately within groups. Missing values are ignored by summary functions; count() counts non-missing values.

Special identifier functions are group() and tag(). They use one or more variables supplied inside the function and do not depend on the by argument. group(site, sex) gives consecutive integer IDs for observed combinations; tag(id) marks the first occurrence of each distinct value.

Value

The edited data frame invisibly. If active data are linked to a visible object through usedf(), that object is updated as well.

Examples

d <- data.frame(
  id = c(1, 1, 2, 3),
  sex = c("F", "F", "M", "M"),
  q1 = c(2, 4, 3, NA), q2 = c(3, 5, 2, 4), q3 = c(4, NA, 1, 5),
  bmi = c(20, 22, 25, 27)
)
egenvar(d, min_score = rowmin(q1:q3),
        max_score = rowmax(q1:q3),
        mean_score = rowmean(q1:q3))

egenvar(d, mean_bmi = mean(bmi), z_bmi = z(bmi), by = sex)
egenvar(d, p75_bmi = pctile(bmi, p = 75), rank_bmi = rank(bmi), by = sex)
egenvar(d, n_group = n(), sequence = seq(), by = sex)
egenvar(d, person_group = group(id, sex), first_id = tag(id))

R4VN documentation built on Sept. 30, 2026, 5:13 p.m.