Is there an R function to reshape this data from long to wide?

You could create a new identifier column with unique value for every student and then use pivot_wider to case multiple columns to wide.

library(dplyr)
df %>%
  mutate(name = as.integer(factor(Student))) %>%
  tidyr::pivot_wider(names_from = name, values_from = c(Student, score))

#  CoachID Student_1 Student_2 Student_3 score_1 score_2 score_3
#    <int> <fct>     <fct>     <fct>       <int>   <int>   <int>
#1       1 A         B         NA              8       3      NA
#2       2 A         B         C               5       4       7

data

df <- structure(list(CoachID = c(1L, 1L, 2L, 2L, 2L), Student = structure(c(1L, 
2L, 1L, 2L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
score = c(8L, 3L, 5L, 4L, 7L)), class = "data.frame", row.names = c(NA, -5L))

Leave a Comment