5
$\begingroup$

I am trying to filter a nested Dataset.

I have some data that looks like this (curated for this example):

h = Dataset@{<|"basicData" -> <|"ID" -> "1008", 
  "dateMMa" -> {2014, 10, 8, 0, 0, 0.`}|>, 
"away" -> <|"City" -> "montréal"|>, 
"home" -> <|"City" -> "toronto"|>|>, <|"basicData" -> <|"ID" -> 
   "1009", "dateMMa" -> {2014, 10, 8, 1, 0, 0.`}|>, 
"away" -> <|"City" -> "philadelphia"|>, 
"home" -> <|"City" -> "boston"|>|>}

I would like to filter this on "dateMMA" for anything earlier than {2014, 10, 8, 1, 0, 0.`} (October 8th 2014). This should yield only one item:

<|"basicData" -> <|"ID" -> "1008",  "dateMMa" -> {2014, 10, 8, 0, 0, 0.`}|>,  "away" -> <|"City" -> "montréal"|>,  "home" -> <|"City" -> "toronto"|>|>

This does not work:

h[[All, "basicData"]][Select[AbsoluteTime@#dateMMa > AbsoluteTime[{2014, 10, 8, 1, 0, 0.`}] &]]

Nor does this:

h[All, "basicData", Select[AbsoluteTime@#dateMMa > AbsoluteTime[{2014, 10, 8, 1, 0, 0.`}] &]]

Nor does this:

h[Select[AbsoluteTime@#dateMMa > AbsoluteTime[{2014, 10, 8, 1, 0, 0.`}] &]]

Is this type of filter/query possible?

Would there be a better way to structure this Dataset to achieve this goal?

$\endgroup$
  • 1
    $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – user9660 Dec 15 '14 at 3:03
7
$\begingroup$

The following query will return the desired result:

h[Select[AbsoluteTime@#["basicData", "dateMMa"] < AbsoluteTime@{2014,10,8,1,0,0} &]]

(* {<|"basicData" -> <|"ID" -> "1008", "dateMMa" -> {2014, 10, 8, 0, 0, 0.}|>, ... |> *)

The vital construction in this solution is #["basicData", "dateMMa"]. It references the nested key dateMMa within the key basicData.

Incidentally, note that < was used instead of > for the date comparison as the text of the question requests anything earlier than the cutoff date.

$\endgroup$
  • $\begingroup$ Worked perfectly! Thank you. The #[key1, key2] notation is new to me. $\endgroup$ – Ray Troy Dec 15 '14 at 14:39
  • $\begingroup$ Indeed, after reading this useful answer, I haven't found a reference for this syntax in the documentation. Maybe it exists, but it's likely not easy to find. $\endgroup$ – faysou Apr 5 '15 at 23:09
  • $\begingroup$ In fact each # in the Select is an association, so this is not a special syntax. Useful post anyway ! $\endgroup$ – faysou Apr 5 '15 at 23:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.