take_x_by_y: Repeat Column Values by Unique Cases in Another Column

View source: R/S03_Utilities.R

take_x_by_yR Documentation

Repeat Column Values by Unique Cases in Another Column

Description

Function to duplicate values in column x by the unique cases in column y. Useful, for example, in extracting and duplicating a subject's baseline values across all time points in a long-form data frame for a longitudinal study.

Usage

take_x_by_y(lfd, x, y, extra = NULL, default = NA, per_row = TRUE)

Arguments

lfd

A long-form data frame.

x

The column with values to duplicate (non-standard evaluation possible).

y

The column to repeat values over (non-standard evaluation possible).

extra

A logical vector matching in length to the number of rows of lfd specifying additional cases to match by when isolating the values of x to repeat.

default

The value to substitute if no cases for x based on extra are found to duplicate.

per_row

Logical; if FALSE returns the associated value of x for each unique value of y, otherwise returns a value of x per each frow of lfd.

Value

A vector matching in length to the number of rows of lfd (for per_row = TRUE) or to the number of unique values of y with the values of x repeated for each unique case of y.

Examples

# Example long-form data frame
lfd <- data.frame(
  ID = rep( 1:3, each = 3 ),
  Value = 1:9,
  Time = rep( 0:2, 3 )
)

# Repeat first value of Y for each value of X
i <- lfd$Time == 0
take_x_by_y( lfd, Value, ID, extra = i )
# Repeat last value of Y for each value of X
i <- lfd$Time == 2
take_x_by_y( lfd, Value, ID, extra = i )
# Per unique case of ID
take_x_by_y( lfd, Value, ID, extra = i, per_row = FALSE )


rettopnivek/arfpam documentation built on Oct. 20, 2024, 7:24 p.m.