简体   繁体   中英

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

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!

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

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
library(tidyverse)

mydf <- tribble(
  ~`Coach ID` , ~Student,  ~score,
  #  ---------------------------------
    1 ,"A" , 8, 
    1 , "B" , 3, 
    2 , "A" , 5,
    2 , "B" , 4,
    2 , "C" , 7
)

mydf <- mydf %>% 
  group_by(`Coach ID`) %>% 
  mutate(index = row_number())


#----- Reshape to wide 

mydf %>% 
  pivot_wider(
    id_cols = `Coach ID`,
    names_from = index,
    values_from = Student:score
    
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM