How to Use spread() Function in R

The spread() function from the tidyr package in R is “used to spread a key-value pair across different columns.” The spread() function also helps reshape the data from a long to a wide format.

Syntax

spread(df, key, value)

Parameters

  1. df: It is the DataFrame.
  2. key: It is the column whose values will become the names of variables or newly created columns.
  3. value: It contains the single-column values for converting to multiple columns.

Return value

It returns a DataFrame or List, depending upon data (argument value).

Example 1: Spread Values Across Two Columns

library(dplyr)
library(tidyr)

# Sample long format dataframe
data_long <- data.frame(
  id = c(1, 1, 2, 2),
  key = c("A", "B", "A", "B"),
  value = c(10, 20, 15, 25)
)

data_wide <- data_long %>% spread(key, value)

print(data_wide)

Output

   id  A   B
1  1  10   20
2  2  15   25

As you can see, the key column has been spread into two columns (A and B), and the values from the value column populate these new columns based on the id and key.

Example 2: Spread Values Across More Than Two Columns

library(dplyr)
library(tidyr)

# Sample long format dataframe with three keys: A, B, and C
data_long <- data.frame(
  id = c(1, 1, 1, 2, 2, 2),
  key = c("A", "B", "C", "A", "B", "C"),
  value = c(10, 20, 30, 15, 25, 35)
)

data_wide <- data_long %>% spread(key, value)

print(data_wide)

Output

   id  A   B   C
1  1  10  20  30
2  2  15  25  35

That’s it!

Related posts

unite() function in R

gather() function in R

arrange() function in R

mutate() function in R

Leave a Comment