首页 > 解决方案 > 是否有一个 R 函数可以将这些数据从长变宽?

问题描述

数据现在的样子:

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

反正有没有将数据从长到宽重塑?

谢谢!

标签: rexcelreshape

解决方案


在基础 R 中,您可以使用以下reshape功能:

reshape(transform(df,time = as.numeric(factor(Student))),idvar = "CoachID",dir = "wide",sep="_")
  CoachID Student_1 score_1 Student_2 score_2 Student_3 score_3
1       1         A       8         B       3      <NA>      NA
3       2         A       5         B       4         C       7

推荐阅读