是否有R函数将数据从长整形重塑为宽?

问题描述 投票:0回答:1

[现在的数据外观:

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

反正有从长到宽的数据重塑形式吗?

谢谢!

r excel reshape
1个回答
0
投票

您可以为每个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))
© www.soinside.com 2019 - 2024. All rights reserved.