reshape_long: Reshape a Wide-Form Data Frame to Long-Form

View source: R/reshape_long.R

reshape_longR Documentation

Reshape a Wide-Form Data Frame to Long-Form

Description

A simple wrapper for Base R reshape with sensible parameter names and sensible defaults, and able to specify a range of variables to transform.

Usage

reshape_long(data, transform, group="Group", response="Response", ID="ID",
           prefix=ID, sep="", shape=c("rect", "square"))

Arguments

data

Data frame that contains the variables to reshape.

transform

The wide-form column variable names to transform to a long-form single column.

group

Name of the grouping variable in the new long-form column.

response

Name of the variable of the response values in the new long-form column.

ID

Name of the newly created ID field in the new long-form column, the original row number from the wide-form. If NULL, then not created.

prefix

The prefix added to the value of ID for each row of data.

sep

Any potential separator of the ID prefix from the given value of the ID.

shape

In general, the input data is a rectangular, wide-form data frame. However, it can also be a symmetric, square correlation or covariance matrix.

Details

reshape_long takes the transform variables in the wide-form from which it creates three new columns, group, response, and ID.

The correspondence between the original reshape parameter names and the reshape_long parameter names is shown in the following table.

reshape reshape_long
----------- ----------------
varying transform
v.names response
timevar group
times transform
idvar ID
----------- ----------------

For a correlation or related symmetric, square input matrix, the applicable parameters are the data parameter to specify the input matrix, group to name the two columns that contain the variable names, and response to specify the name of the variable with data values that are the input correlations or related.

The name entered for group is repeat it for the first two columns output with a suffix of 1 and 2, respectively. For example, group="Item" becomes "Item1" and "Item2". If not name for group is entered, the default variable names are Col and Row.

Author(s)

David W. Gerbing (Portland State University; gerbing@pdx.edu)

See Also

reshape.

Examples

d <- Read("Anova_rb")

# with the default variable names in the long-form
reshape_long(d, c("sup1", "sup2", "sup3", "sup4"))

# with a variable range and custom variable names in the long-form
reshape_long(d, sup1:sup4, group="Supplement", response="Reps", ID="Person")

# input correlation matrix
R <- matrix(nrow=3, ncol=3, byrow=TRUE,
c(1.000,0.480,0.320,
  0.480,1.000,0.240,
  0.320,0.240,1.000))
colnames(R) <- c("X1", "X2", "X3")
rownames(R) <- colnames(R)
# reshape to long
dl <- reshape_long(R, shape="square", group="Item", response="Cor")
dl


lessR documentation built on June 8, 2025, 10:35 a.m.