w2l_nest {mintyr} | R Documentation |
Reshape Wide Data to Long Format and Nest by Specified Columns
Description
The w2l_nest
function reshapes wide-format data into long-format and nests it by specified columns.
It handles both data.frame
and data.table
objects and provides options for grouping and nesting the data.
Usage
w2l_nest(data, cols2l = NULL, by = NULL, nest_type = "dt")
Arguments
data |
|
cols2l |
|
by |
|
nest_type |
|
Details
The function melts the specified wide columns into long format and nests the resulting data by the name
column and any additional grouping variables specified in by
. The nested data can be in the form of
data.table
or data.frame
objects, controlled by the nest_type
parameter.
Both cols2l
and by
parameters accept either column indices or column names, providing flexible ways
to specify the columns for transformation and grouping.
Value
data.table
with nested data in long format, grouped by specified columns if provided. Each row contains a nested data.table
or data.frame
under the column data, depending on nest_type.
If
by
isNULL
, returns adata.table
nested byname
.If
by
is specified, returns adata.table
nested byname
and the grouping variables.
Note
Both
cols2l
andby
parameters can be specified using either numeric indices or character column names.When using numeric indices, they must be valid column positions in the data (1 to ncol(data)).
When using character names, all specified columns must exist in the data.
The function converts
data.frame
todata.table
if necessary.The
nest_type
parameter controls whether nested data aredata.table
("dt"
) ordata.frame
("df"
) objects.If
nest_type
is not"dt"
or"df"
, the function will stop with an error.
See Also
Related functions and packages:
-
tidytable::nest_by()
Nest data.tables by group
Examples
# 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
cols2l = 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
cols2l = 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