Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有R函数将此数据从长到宽进行重塑?_R_Excel_Reshape - Fatal编程技术网

是否有R函数将此数据从长到宽进行重塑?

是否有R函数将此数据从长到宽进行重塑?,r,excel,reshape,R,Excel,Reshape,数据现在的样子: Coach ID | Student | score | --------------------------------- 1 | A | 8 | 1 | B | 3 | 2 | A | 5 | 2 | B | 4 | 2 | C | 7 | 看起来像这样: Coach ID | Student | s

数据现在的样子:

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
是否有办法将数据从长改宽


谢谢

您可以为每个
学生
创建一个具有唯一值的新标识符列,然后使用
pivot\u wide
将多个列的大小写为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
库(dplyr)
df%>%
mutate(name=as.integer(factor(Student)))%>%
tidyr::pivot\u更宽(名称\u from=name,值\u from=c(学生,分数))
#辅导学生1学生2学生3分1分2分3分
#                            
#1 A B NA 8 3 NA
#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))

df在base R中,您可以使用
重塑功能:

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
重塑(转换(df,时间=as.numeric(因子(学生))),idvar=“CoachID”,dir=“wide”,sep=“389;”)
辅导学生1分学生1分学生2分学生3分
1 A 8 B 3 NA
3 2 A 5 B 4 C 7