| w2l_nest | R Documentation |
w2l_nest reshapes a wide-format data.frame or data.table into long
format, then nests the result by name (the pivoted column identifier) and
any optional grouping variables supplied via by. Each row of the returned
table contains a nested data.table or data.frame in the data list-column.
w2l_nest(data, cols = NULL, by = NULL, out_type = "dt")
data |
|
cols |
|
by |
|
out_type |
|
Column resolution: both cols and by accept either integer column
positions or character column names. Out-of-bounds indices and unknown names
are caught early with informative error messages.
Overlap guard: if any column appears in both cols and by, the
function stops with an error before attempting to melt, preventing silent
structural corruption.
Factor-free melting: melt() is called with variable.factor = FALSE
so the name column is always character, avoiding unexpected factor-level
ordering in downstream grouping operations.
No side effects: earlier versions called setDT() on the argument,
which silently turned the caller's data.frame into a data.table. The
input is now left untouched.
Memory efficiency: .SDcols restricts .SD to non-key columns, so
grouping keys are never stored redundantly inside each nested object.
A data.table with one row per combination of name (and by
levels, if provided). The data list-column holds the corresponding
nested data.table or data.frame for each group. Grouping key columns
are never duplicated inside the nested objects.
Passing an empty table (0 rows) triggers a warning() and returns
a 0-row table with the regular column structure
(name, the by columns and data).
name and value are reserved for the long format; data must
not contain other columns with these names.
cols and by must not overlap; overlapping columns will raise
an error.
out_type values other than "dt" or "df" raise an error.
tidytable::nest_by() for a tidyverse-style equivalent.
# Example: Wide to long format nesting demonstrations
# Example 1: Basic nesting by group
w2l_nest(
data = iris, # Input dataset
by = "Species" # Group by Species column
)
# Example 2: Nest specific columns with numeric indices
w2l_nest(
data = iris, # Input dataset
cols = 1:4, # Select first 4 columns to nest
by = "Species" # Group by Species column
)
# Example 3: Nest specific columns with column names
w2l_nest(
data = iris, # Input dataset
cols = c("Sepal.Length", # Select columns by name
"Sepal.Width",
"Petal.Length"),
by = 5 # Group by column index 5 (Species)
)
# Returns similar structure to Example 2
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.