Converting long to wide data in R

In the previous guide, we took a wide data set and converted it to long. While this conversion allowed us to apply some statistical and plotting functions on the data, there may be cases where doing the reverse, going from long to wide, may be useful.

Table 1: Long data format.
idConditionAngleReaction_Time
1Absent0420
1Absent4420
1Absent8480
1Present0480
1Present4600
1Present8780

Converting Long to Wide

1. Unite the Condition and Angle columns

To convert our long format data to the original wide format data frame, we will need to chain a series of commands in the reverse order. Recall that our original wide data frame started out with columns that had the Condition and Angle together and that we had to separate those two variables. We will do the reverse here with the unite() function. We will merge the Condition and Angle column data into one column called Condition.Angle.

wide.data <- 
  long.data %>%
  unite(Condition.Angle, Condition, Angle, sep = "")
Table 2: Joining the condition and angle column cells.
idCondition.AngleReaction_Time
1Absent0420
1Absent4420
1Absent8480
1Present0480
1Present4600
1Present8780

2. Pivot the data

Next, we will use the pivot_wider() function to arrange the values from the Reaction_Time column into separate columns names by the variables in the Condition.Angle columns.

wide.data <- 
  long.data %>%
  unite(Condition.Angle, Condition, Angle, sep = "") %>%
  pivot_wider(names_from = Condition.Angle, values_from = Reaction_Time)
Table 3: Wide data format.
idAbsent0Absent4Absent8Present0Present4Present8
1420420480480600780
2420480480360480600
3480480540660780780
4420540540480780900
5540660540480660720
6360420360360480540
7480480600540720840
8480600660540720900
9540600540480720780
10480420540540660780

3. Remove the id column

Finally, I then selected all columns except id to end up with our original data frame.

wide.data <- 
  long.data %>%
  unite(Condition.Angle, Condition, Angle, sep = "") %>%
  pivot_wider(names_from = Condition.Angle, values_from = Reaction_Time) %>%
  select(-id)
Table 4: Final data frame matching the original chapter_12_table_1 data.
Absent0Absent4Absent8Present0Present4Present8
420420480480600780
420480480360480600
480480540660780780
420540540480780900
540660540480660720
360420360360480540
480480600540720840
480600660540720900
540600540480720780
480420540540660780

References

Kassambara, Alboukadel. 2020a. Rstatix: Pipe-Friendly Framework for Basic Statistical Tests. https://CRAN.R-project.org/package=rstatix.

Maxwell, Scott, Harold Delaney, and Ken Kelley. 2020. AMCP: A Model Comparison Perspective. https://CRAN.R-project.org/package=AMCP.

Wickham, Hadley. 2019. Tidyverse: Easily Install and Load the ’Tidyverse’. https://CRAN.R-project.org/package=tidyverse.

Previous