2

Let's say I have a Dataset consisting of nested Associations (in this case, created through a Query) and I want to convert the first set of Keys into Values. Is there a way to do this without having to drop the Keys, create a new column, and then Join the two together?

Consider the following example where I take the Mean age by sex and class of the passengers in the Titanic ExampleData:

data=ExampleData[{"Dataset", "Titanic"}][GroupBy["class"], 
 GroupBy["sex"] /* KeySort, Mean, #age &]

example dataset

Here is what I am looking for:

enter image description here

And I can get it with this code:

final = Join[AssociationThread["class" -> #] & /@ Keys[data], 
  Values[data], 2]

However, the solution seems like it may take more steps than required. Is there a simpler / more elegant code that I am neglecting?

kickert
  • 1,820
  • 8
  • 22
  • Voted to close as a duplicate. The way to get what you want with the ungroup function from that Q/A answer, is data[ungroup[{"class"}]]. – Leonid Shifrin Nov 05 '19 at 14:46
  • @LeonidShifrin, It might just be me, but that example seems a lot more complicated than even the code I have used above. – kickert Nov 05 '19 at 14:47
  • Well, the general solution given by ungroup might look more complex than your code, but it addresses a general problem, of which yours is a special case. So I would still consider this a duplicate of that. The fact that here Dataset is used and there isn't, matters very little I think. – Leonid Shifrin Nov 05 '19 at 15:13
  • @LeonidShifrin, Thanks for your input. I have spent some time looking through both examples. I certainly see the functional similarities between the questions having missed the earlier question b/c my prior searches focused on Dataset, Key and Value. Ultimately, I was looking for a simpler approach and in this case, ungroup isn't that. I do agree that your approach is more universal. Have you considered submitting to the function repository so it would in fact be a simple solution for a variety of situations? – kickert Nov 05 '19 at 15:20
  • Well, I can retract the close vote if you prefer - let me know. Re: WFR - I might at some point, yes. – Leonid Shifrin Nov 05 '19 at 15:23
  • @LeonidShifrin, I think our conversation, and the input on the other question, probably indicates that the answer to my question is "No, there isn't a simpler way." That being said, it has give me a lot to think about on how to approach the problem when it is nested even deeper. Thanks again for the insights. – kickert Nov 05 '19 at 15:30
  • 1
    Sure, was glad to help. Simplicity is a subjective matter. From some perspective, a more general solution might actually be simpler conceptually (not saying here it is necessarily the case). – Leonid Shifrin Nov 05 '19 at 15:33

0 Answers0