# In Wolfram Mathematica, who do I query the result of a Counts operation efficiently and conveniently?

Setup

Say, I'm given a dataset, like the one below:

titanic = ExampleData[{"Dataset", "Titanic"}]; titanic

And I want to count the occurrences of any combination between { "1st", "2nd"} and {"female", "male"}, using the Counts operator on the dataset, like:

genderclasscounts = titanic[All, {"class", "sex"}][Counts]

Problem statement

This is not a "flat" dataset and I don't have a clue how to query in the usual way, like:

genderclasscount[Select[ ... ], ...]

The resulting dataset doesn't provide "column" names to be used as parameters in the Select nor can I refer to the number representing the count by a name.

And I've no clue how to express an Association as a value in a Select!?

Furthermore, try genderclasscount[Print], this demonstrates the values presented to the operation over this dataset are just numbers!

An unsatisfactory attempt

Of course, I can "flatten" the Counts result, by doing something horrific and inefficient like:

temp = Dataset[(row \[Function]
AssociationThread[{"class", "sex", "count"} -> row]) /@ (Nest[
Normal, genderclasscounts, 3] /.
Rule[{Rule["class", class_], Rule["sex", sex_]},
count_] -> {class, sex, count})]


In this form it is easy to query a count result:

First@temp[Select[#class == "1st" \[And] #sex == "female" &], "count"]

Question

So, my questions are

1. How can I query the (immediate) result of the Count operation in a convenient and efficient fashion, like using a Select operation on the resulting dataset? Or, if that is not possible;

2. Is there an efficient and convenient transformation of the Counts result dataset possible facilitating such a query? With "convenient" I mean, for example, that you just provide the dataset and the transformation handles the rest. So, not something like I've shown above in my unsatisfactory "solution" ;-)

Thanks for reading this far and I'm looking forward to anwsers and inspiration.

/@nanitous

titanic[KeyValueMap[Append[#, "counts" -> #2] &]@*Counts, {"class", "sex"}]

• @nanitous, thank you for the accept. Re reasoning behind, squinting at Normal[titanic[Counts,{"class", "sex"}] realized something like KeyValueMap might work.