9
$\begingroup$

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

$\endgroup$
3
  • $\begingroup$ 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. $\endgroup$ May 15, 2015 at 8:05
  • $\begingroup$ Already submitted to WRI tech support. Hopefully b/w MissingBehavior, PartBehavior and FailureAction can rescue it. $\endgroup$ May 15, 2015 at 18:22
  • $\begingroup$ @GordonCoale, I think MissingBehavior should handle this option. Will contact support. $\endgroup$ Jul 13, 2016 at 19:54

1 Answer 1

5
$\begingroup$
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

$\endgroup$
3
  • $\begingroup$ 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]; $\endgroup$ Jan 18, 2017 at 19:32
  • $\begingroup$ I belatedly noted some limitations of FilterRules in Q you linked above. $\endgroup$ Feb 8, 2017 at 19:09
  • $\begingroup$ @alancalvitti since no one is using FilterRules there maybe it is better to mention it here. $\endgroup$
    – Kuba
    Feb 8, 2017 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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