# decompose: Decompose a Numeric Vector by Group In quest: Prepare Questionnaire Data for Analysis

## Description

`decompose` decomposes a numeric vector into within-group and between-group components via within-group centering and group-mean aggregation. There is an option to create a grand-mean centered version of the between-person component as well as lead/lag versions of the original vector and the within-group component.

## Usage

 `1` ```decompose(x, grp, grand = TRUE, n.shift = NULL, undefined = NA) ```

## Arguments

 `x` numeric vector. `grp` list of atomic vector(s) and/or factor(s) (e.g., data.frame), which each have same length as `x`. It can also be an atomic vector or factor, which will then be made the first element of a list internally. `grand` logical vector of length 1 specifying whether a grand-mean centered version of the the between-group component should be computed. `n.shift` integer vector specifying the direction and magnitude of the shifts. For example a one-lead is +1 and a two-lag is -2. See `shift` details. `undefined` atomic vector with length 1 (probably makes sense to be the same typeof as `x`). Specifies what to insert for undefined values after the shifting takes place. See `shift` details.

## Value

data.frame with nrow = `length(x)` and ```row.names = names(x)```. The first two columns correspond to the within-group component (i.e., "wth") and the between-group component (i.e., "btw"). If grand = TRUE, then the third column corresponds to the grand-mean centered between-group component (i.e., "btw_c"). If shift != NULL, then the last columns are the shifts indicated by n.shift, where the shifts of `x` are first (i.e., "tot") and then the shifts of the within-group component are second (i.e., "wth"). The naming of the shifted columns is based on the default behavior of `Shift_by`. See the details of `Shift_by`. If you don't like the default naming, then call `Decompose` instead and use the different suffix arguments.

`decomposes` `center_by` `agg` `shift_by`
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16``` ```# single grouping variable chick_data <- as.data.frame(ChickWeight) # because the "groupedData" class # calls `[.groupedData`, which is different than `[.data.frame` decompose(x = ChickWeight[["weight"]], grp = ChickWeight[["Chick"]]) decompose(x = ChickWeight[["weight"]], grp = ChickWeight[["Chick"]], grand = FALSE) # no grand-mean centering decompose(x = setNames(obj = ChickWeight[["weight"]], nm = paste0(row.names(ChickWeight),"_row")), grp = ChickWeight[["Chick"]]) # with names # multiple grouping variables tmp_nm <- c("Type","Treatment") # b/c Roxygen2 doesn't like c() in a [] decompose(x = as.data.frame(CO2)[["uptake"]], grp = as.data.frame(CO2)[tmp_nm]) decompose(x = as.data.frame(CO2)[["uptake"]], grp = as.data.frame(CO2)[tmp_nm], n.shift = 1) decompose(x = as.data.frame(CO2)[["uptake"]], grp = as.data.frame(CO2)[tmp_nm], n.shift = c(+2, +1, -1, -2)) ```