The “spread” Function in R

  • Package: tidyr

  • Purpose: To reshape 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.

    • key: The name of the column containing the keys (to spread into columns).

    • value: The name of the column containing the values (to fill the new columns).

  • Notable Optional Arguments:

    • None.

  • Example (with Explanation):

  • # Load necessary packages
    library(tidyr)

    # Create a sample data frame
    data <- data.frame(
    ID = c(1, 2, 1, 2),
    fruit = c("Apple", "Apple", "Orange", "Orange"),
    value = c(10, 15, 20, 25)
    )

    # Spread the 'fruit' column into multiple columns
    result <- spread(data, key = fruit, value = value)

    # Display the result
    print(result)

  • In this example, the spread function from the tidyr package is used to reshape the sample data frame data from long to wide format. The fruit column is spread into multiple columns, with each unique value in the fruit 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 “separate” Function in R

Next
Next

The “gather” Function in R