The “gather” Function in R

  • Package: tidyr

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

  • General Class: Data Reshaping

  • Required Argument(s):

    • data: The data frame to reshape.

    • key: The name of the new column that will store the keys (column names).

    • value: The name of the new column that will store the values.

  • Notable Optional Arguments:

    • ...: Names of columns to gather. If not provided, all columns not specified in key will be gathered.

  • Example (with Explanation):

  • # Load necessary packages
    library(tidyr)

    # Create a sample data frame
    data <- data.frame(
    ID = 1:3,
    Apple = c(10, 15, 20),
    Orange = c(25, 30, 35)
    )

    # Gather columns into key-value pairs
    result <- gather(data, fruit, value, -ID)

    # Display the result
    print(result)

  • In this example, the gather function from the tidyr package is used to reshape the sample data frame data from wide to long format. The ID column is kept as is, while the Apple and Orange columns are gathered into key-value pairs, with the keys stored in a new column called fruit and the values stored in a new column called value. The result is a new data frame result containing the reshaped data.

Previous
Previous

The “spread” Function in R

Next
Next

The “na_if” Function in R