Pivots the levels of one column (names_from, e.g. environment, farm or test station) into separate columns for every trait in cols, aligning records by the identifier columns id (e.g. the animal ID). The result is nested by trait, ready for iterative analyses such as genetic correlations of the same trait across environments.

r2p_nest(data, names_from, cols, out_type = "dt", id = NULL)

Arguments

data

Input data.frame or data.table. It is never modified.

names_from

A single column name or index whose levels become columns.

cols

A character vector of column names or numeric indices: the trait columns to pivot.

out_type

Output nesting format ("dt" or "df"). Default "dt".

id

Identifier column(s) used to align rows across levels of names_from. Default NULL uses all columns that are neither in cols nor names_from (a message lists them); supplying id explicitly is strongly recommended.

Value

A nested data.table with columns name (trait) and data. Each nested table holds the id columns plus one column per level of names_from.

Details

The combination of id and names_from must identify every row uniquely. Otherwise dcast() would aggregate duplicated records with length() and silently replace trait values by counts; the function stops instead.

Other trait columns in cols are never used as identifiers: their values differ between environments and would prevent any pairing.

Examples

# Example: the same traits recorded on the same animals in two farms
set.seed(1)
growth <- data.frame(
  animal = rep(sprintf("A%02d", 1:6), each = 2),
  farm   = rep(c("farm1", "farm2"), times = 6),
  adg    = round(rnorm(12, 900, 50)),     # average daily gain
  bf     = round(rnorm(12, 11, 1.5), 1)   # backfat
)

# Example 1: column names
r2p_nest(
  growth,
  names_from = "farm",           # levels become columns: farm1, farm2
  cols      = c("adg", "bf"),    # traits to pivot
  id        = "animal"           # aligns records of the same animal
)
#>      name              data
#>    <char>            <list>
#> 1:    adg <data.table[6x3]>
#> 2:     bf <data.table[6x3]>
# Returns a nested data.table where:
# - name: trait names (adg, bf)
# - data: one row per animal with columns animal, farm1, farm2

# Example 2: numeric indices
r2p_nest(growth, names_from = 2, cols = 3:4, id = 1)
#>      name              data
#>    <char>            <list>
#> 1:    adg <data.table[6x3]>
#> 2:     bf <data.table[6x3]>