17.1 C
London
Saturday, July 26, 2025
HomeStatistics TutorialRHow to Use pivot_wider() in R

How to Use pivot_wider() in R

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories