The pivot_wider() function from the tidyr package in R can be used to pivot a data frame from a long format to a wide format.
This function uses the following basic syntax:
library(tidyr)
df %>% pivot_wider(names_from = var1, values_from = var2)
where:
- names_from: The column whose values will be used as column names
- values_from: The column whose values will be used as cell values
The following example shows how to use this function in practice.
Related: Long vs. Wide Data: What’s the Difference?
Example: Use pivot_wider() in R
Suppose we have the following data frame in R that contains information about various basketball players:
#create data frame df frame(player=rep(c('A', 'B'), each=4), year=rep(c(1, 1, 2, 2), times=2), stat=rep(c('points', 'assists'), times=4), amount=c(14, 6, 18, 7, 22, 9, 38, 4)) #view data frame df player year stat amount 1 A 1 points 14 2 A 1 assists 6 3 A 2 points 18 4 A 2 assists 7 5 B 1 points 22 6 B 1 assists 9 7 B 2 points 38 8 B 2 assists 4
We can use the pivot_wider() function to pivot this data frame into a wide format:
library(tidyr)
#pivot the data frame into a wide format
df %>% pivot_wider(names_from = stat, values_from = amount)
# A tibble: 4 x 4
player year points assists
1 A 1 14 6
2 A 2 18 7
3 B 1 22 9
4 B 2 38 4
Notice that the values from the stat column are now used as column names and the values from the amount column are used as cell values in these new columns.
The final result is a wide data frame.
Note: You can find the complete documentation for the pivot_wider() function here.
Additional Resources
The following tutorials explain how to use other common functions in the tidyr package in R:
How to Use Spread Function in R
How to Use Gather Function in R
How to Use Separate Function in R
How to Use the Unite Function in R