The “pivot_longer” Function in R

  • Package: tidyr

  • Purpose: To pivot data from wide to long format by gathering multiple columns into key-value pairs.

  • General Class: Data Reshaping

  • Required Argument(s):

    • data: The data frame to reshape.

    • cols: Columns to pivot into longer format.

  • Notable Optional Arguments:

    • names_to: The name of the new column that will store the names of the pivoted columns.

    • values_to: The name of the new column that will store the values of the pivoted columns.

    • names_prefix: Prefix to apply to the names of the original columns. The default is NULL.

  • Example (with Explanation):

  • # Load necessary packages
    library(tidyr)

    # Create a sample data frame
    data <- data.frame(
    ID = 1:3,
    Apple_2021 = c(10, 15, 20),
    Orange_2021 = c(25, 30, 35),
    Apple_2022 = c(40, 45, 50),
    Orange_2022 = c(55, 60, 65)
    )

    # Pivot the data from wide to long format
    result <- pivot_longer(data, cols = -ID, names_to = "Fruit_Year", values_to = "Value")

    # Display the result
    print(result)

  • In this example, the pivot_longer function from the tidyr package is used to reshape the sample data frame data from wide to long format. The columns ‘Apple_2021’, ‘Orange_2021’, ‘Apple_2022’, and ‘Orange_2022’ are gathered into key-value pairs, with the names stored in a new column ‘Fruit_Year’ and the values stored in a new column ‘Value’. The result is a new data frame result containing the reshaped data.

Previous
Previous

The “pivot_wider” Function in R

Next
Next

The “unnest” Function in R