Learn R Programming

insight (version 0.15.0)

data_to_long: Reshape (pivot) data from wide to long

Description

This function "lengthens" data, increasing the number of rows and decreasing the number of columns. This is a dependency-free base-R equivalent of tidyr::pivot_longer().

Usage

data_to_long(
  data,
  cols = "all",
  colnames_to = "Name",
  values_to = "Value",
  rows_to = NULL,
  ...,
  names_to = colnames_to
)

data_to_wide( data, values_from = "Value", colnames_from = "Name", rows_from = NULL, sep = "_", ..., names_from = colnames_from )

Arguments

data

A data frame to pivot.

cols

A vector of column names or indices to pivot into longer format.

colnames_to

The name of the new column that will contain the column names.

values_to

The name of the new column that will contain the values of the pivoted variables.

rows_to

The name of the column that will contain the row-number from the original data. If NULL, will be removed.

...

Additional arguments passed on to methods.

names_to, names_from

Same as colnames_to, is there for compatibility with tidyr::pivot_longer().

values_from

The name of the column that contains the values of the put in the columns.

colnames_from

The name of the column that contains the levels to be used as future columns.

rows_from

The name of the column that identifies the rows. If NULL, will use all the unique rows.

sep

The indicating a separating character in the variable names in the wide format.

Value

data.frame

Examples

Run this code
# NOT RUN {
wide_data <- data.frame(replicate(5, rnorm(10)))

# From wide to long
# ------------------
# Default behaviour (equivalent to tidyr::pivot_longer(wide_data, cols = 1:5))
data_to_long(wide_data)

# Customizing the names
data_to_long(wide_data,
  cols = c(1, 2),
  colnames_to = "Column",
  values_to = "Numbers",
  rows_to = "Row"
)

# From long to wide
# -----------------
long_data <- data_to_long(wide_data, rows_to = "Row_ID") # Save row number
data_to_wide(long_data,
  colnames_from = "Name",
  values_from = "Value",
  rows_from = "Row_ID"
)

# Full example
# ------------------
if (require("psych")) {
  data <- psych::bfi # Wide format with one row per participant's personality test

  # Pivot long format
  long <- data_to_long(data,
    cols = "\\d", # Select all columns that contain a digit
    colnames_to = "Item",
    values_to = "Score",
    rows_to = "Participant"
  )

  # Separate facet and question number
  long$Facet <- gsub("\\d", "", long$Item)
  long$Item <- gsub("[A-Z]", "", long$Item)
  long$Item <- paste0("I", long$Item)

  wide <- data_to_wide(long,
    colnames_from = "Item",
    values_from = "Score"
  )
  head(wide)
}
# }

Run the code above in your browser using DataLab