How can the Mathematica 11.3 module below be improved (it builds a frequency table)? The data source is a Dataset object (dbase) and the row/column variables are respectively rowDIN and colDIN. Here the table entries would give the grade distribution within subject.
Dataset's documentation has an example that suggests a solution (see the line titanic[GroupBy["sex"],GroupBy["class"],ratio,"survived"]). Although I've tweaked this to get the desired table, it works because the table has no zeros. When applied to another database whose table would have zeros, Mathematica doesn't return a table -- that's why I use Count below.
There must be an easier way, and hopefully someone here knows it. Thanks.
myTable[dbase_, rowDIN_, colDIN_] := Module[{
columns = Sort@Normal@DeleteDuplicates@dbase[[All, colDIN]],
group,
X = GroupBy[dbase, rowDIN]},
X = (group = #; {group[[1, rowDIN]],
Count[Normal@group[[All, colDIN]], #] & /@ columns}) & /@ X;
X = X // Normal // Normal // Last /@ # &;
Grid@Prepend[Flatten /@ X, Prepend[columns, rowDIN]]];
myTable[schoolInfo, "Subject", "Grade"]
where
schoolInfo = Dataset@{<|"Subject" -> "XYZ",
"Grade" -> "A"|>, <|"Subject" -> "XYZ",
"Grade" -> "B"|>, <|"Subject" -> "XYZ",
"Grade" -> "A"|>, <|"Subject" -> "ABC",
"Grade" -> "A"|>, <|"Subject" -> "ABC",
"Grade" -> "C"|>, <|"Subject" -> "ABC",
"Grade" -> "C"|>, <|"Subject" -> "ABC", "Grade" -> "A"|>}
(J.M., I'm sorry for posting the wrong dataset a moment ago. The above is correct.)