| r2p_nest | R Documentation |
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)
data |
Input |
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 ( |
id |
Identifier column(s) used to align rows across levels of
|
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.
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.
# 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
)
# 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.