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

断了今生、忘了曾经 提交于 2021-01-30 02:38:32

问题


How the data looks now:

Coach ID | Student | score |
---------------------------------
1         | A      | 8     |
1         | B      | 3     |  
2         | A      | 5     |
2         | B      | 4     |
2         | C      | 7     |

To look like this:

Coach ID | Student | score | student_2|score_2| student_3|score_3
------------------------------------------------------------------
1         | A      | 8     | B        | 3     |   
2         | A      | 5     | B        | 4     | C        | 7

Is there anyway to reshape data from long to wide?

Thanks!


回答1:


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))



回答2:


In base R, you could use the reshape function:

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


来源:https://stackoverflow.com/questions/60087414/is-there-an-r-function-to-reshape-this-data-from-long-to-wide

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!