-3

I have a matrix like following table (the matrix is big consists of 16 years suppose for GPA of 100 students A,B,C,D...)

  `Year    GPA   Student
1   1996    3.2    A
2   1997    3.3    A
3   1998    3.5    A
4   1999     4     A
5   1996     3     B
6   1997     3     B
7   1998     4     B
8   1999    3.5    B
9   1996     4     C
10  1997     3     C
11  1998     2     C
12  1999     3     C 

I want to use BICC function in R so I need to change my matrix to something like this :

         `A     B     C
 `1996   3.2    3     4
  1997   3.2    3     3
  1998   3.3    4     2
  1999   3.5   3.5    3

in this table "Year" variable goes as row (row name ?) and students names go to colname in R . Thank you .

Nim
  • 7
  • 2

1 Answers1

-1

We can use xtabs from base R to do this

xtabs(GPA~Year + Student, df1)
#      Student
#Year     A   B   C
#  1996 3.2 3.0 4.0
#  1997 3.3 3.0 3.0
#  1998 3.5 4.0 2.0
#  1999 4.0 3.5 3.0

Or with acast from reshape2

library(reshape2)
acast(df1, Year~Student, value.var = "GPA", fun.aggregate = sum)

NOTE: with acast, we can change the fun.aggregate to sum, or mean or any other function. In xtabs, it does the sum for each 'Year', 'Student' combination (if there are duplicates)

akrun
  • 874,273
  • 37
  • 540
  • 662