To reshape data between wide and long format in R, you can use pivot_wider() and pivot_longer() function from tidyr library.
The following methods show how you can do it with syntax.
Method 1: Use pivot_longer() Function
library(tidyr)
pivot_longer(df, cols = everything())
Method 2: Use pivot_wider() Function
library(tidyr)
pivot_wider(df, names_from=group, values_from=c(column1, column2))
The following examples show how to reshape data between wide and long format in R.
Using pivot_longer() Function
Let’s see how we ca reshape dataframe to long format using pivot_longer() function in R:
# Import library
library(tidyr)
# Create dataframe
df <- data.frame(Pressure1=c(12,13,11,9,8,7),
Pressure2=c(78,89,85,84,81,79))
# Create pivot table
df_long <- pivot_longer(df, cols = everything())
# Print pivot table
print(df_long)
Output:
name value
<chr> <dbl>
1 Pressure1 12
2 Pressure2 78
3 Pressure1 13
4 Pressure2 89
5 Pressure1 11
6 Pressure2 85
7 Pressure1 9
8 Pressure2 84
9 Pressure1 8
10 Pressure2 81
11 Pressure1 7
12 Pressure2 79
Here the output shows longer format of dataframe which created using pivot_longer() function.
Use pivot_wider() Function
Let’s see how to 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
In the output it shows wider format of dataframe which created using pivot_wider() function. Here we group data based on player column of data frame.