The “pivot_wider” Function in R

  • Package: tidyr

  • Purpose: To pivot data from long to wide format by spreading a key-value pair into multiple columns.

  • General Class: Data Reshaping

  • Required Argument(s):

    • data: The data frame to reshape.

    • names_from: The name of the column containing the values that will become column names.

    • values_from: The name of the column containing the values to fill the new columns.

  • Notable Optional Arguments:

    • values_fill: The value to use for filling in missing combinations. The default is NA.

  • Example (with Explanation):

  • # Load necessary packages
    library(tidyr)

    # Create a sample data frame
    data <- data.frame(
    ID = c(1, 2, 3),
    Year = c("2020", "2020", "2021"),
    Value = c(10, 15, 20)
    )

    # Pivot the data from long to wide format
    result <- pivot_wider(data, names_from = Year, values_from = Value)

    # Display the result
    print(result)

  • In this example, the pivot_wider function from the tidyr package is used to reshape the sample data frame data from long to wide format. The ‘Year’ column is spread into multiple columns, with each unique value in the ‘Year’ column becoming a new column header. The values from the ‘Value’ column are then filled into the corresponding new columns. The result is a new data frame result containing the reshaped data.

Previous
Previous

The “expand” Function in R

Next
Next

The “pivot_longer” Function in R