9

This Q is related to this one, but now refer to the situation as irregularly distributed Keys in lists of Associations:

data4 = {<|"a" -> 1, "b" -> 2|>, <|"a" -> 3, "c" -> 4|>} // Dataset

Consider:

data4[All, {"a" -> Framed, "b" -> Panel}] 

enter image description here

Of course this fails altogther:

data4[All, {"a" -> Framed, "b" -> Panel, "c" -> (Style[#, Red] &)}]

{Missing["Failed"], Missing["Failed"]}

Is there a better way than this clearly inefficient workaround using Lookup and subsequent filter out based on matching Missing? - To avoid having to add Missing handlers for each function:

data4[All, ({"a", "b", "c"} // AssociationMap[Lookup]) /* 
    Query[{"a" -> Framed, "b" -> Panel, "c" -> (Style[#, Red] &)}]][
  All, Select[FreeQ[#, Missing["KeyAbsent", "a" | "b" | "c"]] &]] // Normal

enter image description here

alancalvitti
  • 15,143
  • 3
  • 27
  • 92
  • I wonder if its worth talking to Wolfram - it may be possible that the MissingBehaviour option of Query could be amended to deal with this, or that Query needs some additional intelligence to handle non uniform keys. – Gordon Coale May 15 '15 at 08:05
  • Already submitted to WRI tech support. Hopefully b/w MissingBehavior, PartBehavior and FailureAction can rescue it. – alancalvitti May 15 '15 at 18:22
  • @GordonCoale, I think MissingBehavior should handle this option. Will contact support. – alancalvitti Jul 13 '16 at 19:54

1 Answers1

5
data4 = {<|"a" -> 1, "b" -> 2|>, <|"a" -> 3, "c" -> 4|>} // Dataset

You could go with the answer from Query or MapAt ragged associations or ignoring Missing values

but let's create something more general since retyping keys is ugly:

mapping = {"a" -> Framed, "b" -> Panel, "c" -> (Style[#, Red] &)};

data4[
 All,
 Query[  FilterRules[mapping, #] ][#] &
]

enter image description here

Kuba
  • 136,707
  • 13
  • 279
  • 740
  • That works nicely - interesting that FilterRules has been around pre v10. Heres's a slightly cleaned up version: filter[expr_][as_Association] := Query[FilterRules[expr, as]][as]; – alancalvitti Jan 18 '17 at 19:32
  • I belatedly noted some limitations of FilterRules in Q you linked above. – alancalvitti Feb 08 '17 at 19:09
  • @alancalvitti since no one is using FilterRules there maybe it is better to mention it here. – Kuba Feb 08 '17 at 19:31