1

I have data as below:

    Stage Month
1       4   Jun
2       1   Jun
3       3   Jun
4       4   Jun
5       4   Jun
6       3   Jun
7       2   Jun
8       4   Jun
9       5   Jun
10      5   Jun
11      4   Jul
12      3   Jul
13      1   Jul
14      2   Jul
15      5   Jul
16      3   Jul
17      3   Jul
18      2   Jul

and I need to change it around so categories of stage become column headings and occurrences of each stage are summed for each month like this:

      1  2  3  4  5
Jun   1  1  2  4  2
Jul   1  2  3  1  1

I've tried everything I know like aggregate() etc. but I've hit my R limit. Thanks for any help!

Mackle
  • 11
  • 1
  • `table(df)` should be enough. – Ronak Shah Dec 06 '19 at 11:13
  • I'm guessing your table is stored as a data frame, so this is a data table solution that works: `library(data.table)` `myData <- data.frame(Stage = c(4,1,3,4,4,3,2,4,5,5,4,3,1,2,5,3,3,2), Month = c(rep("Jun", 10), rep("Jul", 8)))` `setDT(myData)` `myData <- dcast(myData, Month ~ Stage, value.var = "Stage", fun.aggregate = length)` `myData <- myData[order(match(Month, month.abb))]` – sehock Dec 06 '19 at 14:02

0 Answers0