BoxWhiskerChart by Categorical Variable

I visit:

Then I select all of the lottery data and paste and save it in a file named lottery.txt on my system. I can then import the file in Mathematica via:

lotterydata = Import["/Users/davidarnold/Documents/temp/lottery.txt","Table"];


Now, if I were using RStudio and R, where the data set includes the headers (which I didn't include in my Mathematica attempt), I could create box plots for each month with the following command.

boxplot(Draft_No. ~ Mo.Number, data=lotterydata)

Which would produce this image.

What is the simplest way I can do this in Mathematica?

I've come up with a method:

months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
data = Table[
Cases[lotterydata, {_, _, m, _, num_} -> num], {m, 1, 12}];
BoxWhiskerChart[data,
ChartStyle -> 10,
ChartLabels -> months]


Which produces this image:

Still, is there a simpler way? This was a real struggle to figure this out.

2 Answers

I think GatherBy (docs) is what you are looking for. The following expression gathers the data in the plot in separate sublists according to the value of the second element in each sublist, which in your case is the month name (the same results could be obtained with the third element, i.e. the month number).

I then generated the chart labels from the second column in the data, i.e. the month labels, by extracting it out and applying DeleteDuplicates (docs) to it.

BoxWhiskerChart[
GatherBy[lotterydata, #[[2]]&][[All, All, 5]],
ChartStyle -> 10,
ChartLabels -> DeleteDuplicates[lotterydata[[All, 2]]]
]


SemanticImport can help you easily generate a Dataset that is similar to R's data frames.

lottery = Import["http://lib.stat.cmu.edu/DASL/Datafiles/DraftLottery.html", "XMLObject"];
First @ Cases[lottery, XMLElement["pre", _, {d_}] :> d, Infinity];
SemanticImportString[%];
Query[GroupBy[#Month &], All, "Draft_No."] @ %;
BoxWhiskerChart[%, ChartLabels -> Automatic, ChartStyle -> 10]