The pivot_wider() function from reshape2 package is used to reshape dataframe from longer to wider format. When you want to pivot multiple columns, you can specify the columns you want to pivot using the values_from argument.
The following method shows how you can do it with syntax.
Method 1: Use pivot_wider() Function
library(tidyr)
pivot_wider(df, names_from=group, values_from=c(column1, column2))
The following example shows how to use pivot_wider() function to reshape data frame from longer to wider format.
Using pivot_wider() Function
Let’s see how we can use pivot_wider() function in R:
# Import package
library(tidyr)
# Create dataframe
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B'),
player=c('G', 'F', 'C', 'G', 'F', 'C'),
points=c(22, 34, 20, 15, 14, 19),
assists=c(4, 10, 12, 9, 8, 5))
# Create wider pivot table
df_wide <- pivot_wider(df, names_from=player, values_from=c(points, assists))
# Print wider table
print(df_wide)
Output:
team points_G points_F points_C assists_G assists_F assists_C
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A 22 34 20 4 10 12
2 B 15 14 19 9 8 5
Here the output shows pivot table in wider format which created from multiple columns of dataframe.