shapevar: Reshape Data Between Wide and Long Formats

View source: R/shapevar.R

shapevarR Documentation

Reshape Data Between Wide and Long Formats

Description

Converts repeated-measures data from wide to long format or from long to wide format using base R only. The active R4VN data frame is used when data is omitted.

Usage

shapevar(
  to = NULL,
  long = FALSE,
  wide = FALSE,
  id,
  vars,
  time = time,
  value = value,
  times = NULL,
  sep = "_",
  data = NULL,
  quiet = FALSE
)

Arguments

to

Optional target shape: "long" or "wide". The shorter R4VN-style alternatives long = TRUE and wide = TRUE are also supported.

long, wide

Logical shortcuts. Use exactly one when to is omitted.

id

One or more subject/record identifier variables. Use a bare name or vars(...).

vars

Variables to reshape, usually supplied by vars(...).

time

Name of the time/index variable. In wide-to-long conversion this is the new time variable; in long-to-wide conversion it is an existing variable.

value

Name of the new value variable for wide-to-long conversion. Ignored for long-to-wide conversion.

times

Optional values assigned to the repeated wide columns. When omitted, shapevar() tries to infer suffixes from the selected variable names and otherwise uses ⁠1, 2, ...⁠.

sep

Separator between value-variable names and time values when creating wide variable names.

data

Optional explicit data-frame object. When omitted, active data is reshaped and replaced directly.

quiet

Logical; suppress the reshape summary.

Details

Wide to long example:

⁠shapevar(long = TRUE, id = id, vars = vars(bp1, bp2, bp3),⁠ ⁠ time = visit, value = bp)⁠

Long to wide example:

shapevar(wide = TRUE, id = id, time = visit, vars = vars(bp))

For long-to-wide conversion, each id by time combination must be unique. Variables not included in vars are preserved when they are constant within each ID. A changing non-reshaped variable triggers an error rather than being silently discarded.

Value

The reshaped data frame invisibly.

Examples

wide <- data.frame(id = 1:2, sex = c("F", "M"),
                   bp1 = c(120, 130), bp2 = c(118, 128), bp3 = c(116, 125))
usedf(wide, quiet = TRUE)
shapevar(long = TRUE, id = id, vars = vars(bp1, bp2, bp3),
         time = visit, value = bp, quiet = TRUE)
long <- usedf(quiet = TRUE)
shapevar(wide = TRUE, id = id, time = visit, vars = vars(bp), quiet = TRUE)

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