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
- df: It is the DataFrame.
- key: It is the column whose values will become the names of variables or newly created columns.
- 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

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.