| w2l_split | R Documentation |
w2l_split reshapes a wide-format data.frame or data.table into long
format, then splits the result into a named list keyed by the pivoted column
identifier (variable) and any optional grouping variables supplied via
by. List element names are derived directly from the grouping key
combinations produced by split(), guaranteeing name-to-content alignment.
w2l_split(data, cols = NULL, by = NULL, out_type = "dt", sep = "_")
data |
|
cols |
|
by |
|
out_type |
|
sep |
|
Name safety: list names are built from each element's own key values
(joined by sep), so names always match contents. This also makes sep
work on every data.table version (split(sep = ) is only honoured from
data.table 1.16.0 on).
Column resolution: both cols and by accept integer column
positions or character column names. Out-of-bounds indices and unknown names
are caught early with informative error messages.
Overlap guard: columns appearing in both cols and by raise an
error before melting to prevent id.vars / measure.vars conflicts.
Factor-free melting: melt() is called with variable.factor = FALSE
so the variable column is always character, keeping split() sort order
consistent with lexicographic expectations.
Memory efficiency: the elements returned by split() are independent
objects, so for out_type = "df" they are converted in place with
setDF() and no column vector is duplicated. The input itself is never
modified.
A named list of data.table or data.frame objects (controlled by
out_type). Names reflect the key combination of variable (and by
levels if provided), joined by sep.
If by is NULL, the list is keyed by the pivoted column names only.
If by is specified, the list is keyed by variable and all by
level combinations.
An empty input table (0 rows) triggers a warning() and returns an
empty list immediately.
cols and by must not overlap; shared columns raise an error.
out_type values other than "dt" or "df" raise an error.
tidytable::group_split() for a tidyverse-style equivalent.
# Example: Wide to long format splitting demonstrations
# Example 1: Basic splitting by Species
w2l_split(
data = iris, # Input dataset
by = "Species" # Split by Species column
) |>
lapply(head) # Show first 6 rows of each split
# Example 2: Split specific columns using numeric indices
w2l_split(
data = iris, # Input dataset
cols = 1:3, # Select first 3 columns to split
by = 5 # Split by column index 5 (Species)
) |>
lapply(head) # Show first 6 rows of each split
# Example 3: Split specific columns using column names
list_res <- w2l_split(
data = iris, # Input dataset
cols = c("Sepal.Length", # Select columns by name
"Sepal.Width"),
by = "Species" # Split by Species column
)
lapply(list_res, head) # Show first 6 rows of each split
# Returns similar structure to Example 2
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.