[现在的数据外观:
Coach ID | Student | score |
---------------------------------
1 | A | 8 |
1 | B | 3 |
2 | A | 5 |
2 | B | 4 |
2 | C | 7 |
看起来像这样:
Coach ID | Student | score | student_2|score_2| student_3|score_3
------------------------------------------------------------------
1 | A | 8 | B | 3 |
2 | A | 5 | B | 4 | C | 7
反正有从长到宽的数据重塑形式吗?
谢谢!
您可以为每个student
创建一个具有唯一值的新标识符列,然后使用pivot_wider
将多列设置为宽大。
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
数据
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))