tidyr:: pivot_longer()

  • pivot_longer() function is part of the tidyr package,
  • pivot_longer() lengthens data by increasing the number of rows and decreasing the number of columns
  • Reshapes a dataset from a wide format to a longer format.
  • Transforms multiple columns into key-value pairs, making data more suitable for analysis and visualization.
  • Commonly used to tidy data for easier manipulation and modeling.

Syntax

  • data: The data frame you want to reshape.
  • cols: Columns to be reshaped from wide to long format.
  • ...: Additional arguments that allow you to specify the names of columns to reshape (cols), and other parameters like names_to and values_to.
  • cols_vary: Specifies how columns should be treated if they have different lengths. Options include “warn”, “strict”, and “everything”. Default is “fastest”, which is the fastest approach but assumes that all columns have the same length.
  • names_to: The name of the new column that will store the variable names. Default is “name”.
  • names_prefix: A character vector of length 1 that specifies a prefix to be added to the variable names.
  • names_sep: A character vector of length 1 that specifies a separator to be used between variable names and the values in the resulting “name” column.
  • names_pattern: A regular expression pattern used to extract variable names from existing column names. This argument is useful when variable names are embedded in column names.

Key Arguments:

  1. data: The data frame or tibble to be reshaped.
  2. cols: The names of the columns to be transformed into key-value pairs. Can be specified as:
    • Column names (e.g., cols = c("col1", "col2"))
    • Number ranges (e.g., cols = 2:4)
    • Patterns using matches() (e.g., cols = matches("^var"))
  3. names_to: The name of the new column that will hold the variable names (keys).
  4. values_to: The name of the new column that will hold the corresponding values.

Example: view the longer table version here.

Example 2: Real Data from mpg

Now, let us convert this table to a long table here.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top