5
$\begingroup$

Association keys are supposed to be transparent, but in this reduced example SplitBy fails:

ds = <|t1 -> <|"a" -> 1|>, t2 -> <|"a" -> 1|>, t3 -> <|"a" -> 2|> |>

This works:

ds // Values // SplitBy[#, #a &]&

{{<|"a" -> 1|>, <|"a" -> 1|>}, {<|"a" -> 2|>}}

But the following fail for the same reason:

ds // SplitBy[#, #a &] &

ds // Map[Normal] // SplitBy[#, #a &]&

Split::normal: "Nonatomic expression expected at position 1 in !(Split[<|t1 -> {\"a\" -> 1}, t2 -> {\"a\" -> 1}, t3 -> {\"a\" -> 2}|>, ((#a &))[#1] === ((#a &))[#2] &]). "

Is there a workaround that doesn't involve injecting keys t1, t2 etc as key-value pairs in each row?

$\endgroup$
  • $\begingroup$ SplitBy expects a List as the first argument, no? $\endgroup$ – chuy Oct 13 '15 at 21:38
9
$\begingroup$

SplitBy is implemented in terms of Split which does not work on associations:

Split[ds]

During evaluation of Split::normal: Nonatomic expression expected at position 1 in Split[<|t1-><|a->1|>,t2-><|a->1|>,t3-><|a->2|>|>]. >>

So I think you will have to convert to a list

SplitBy[List @@ ds, #a &]

(* {{<|"a" -> 1|>, <|"a" -> 1|>}, {<|"a" -> 2|>}} *)

If you need to retain the keys you could use something like:

SplitBy[Normal@ds, #a& @* Last]

(* {{t1 -> <|"a" -> 1|>, t2 -> <|"a" -> 1|>}, {t3 -> <|"a" -> 2|>}} *)
$\endgroup$
  • $\begingroup$ Unfortunately that projects the keys out and there's no easy way to sync them to the processed list. $\endgroup$ – alancalvitti Oct 13 '15 at 20:56
  • $\begingroup$ Thanks for the edit, composing with Last works. $\endgroup$ – alancalvitti Oct 13 '15 at 21:17
  • $\begingroup$ Values also works in place of Last $\endgroup$ – alancalvitti Oct 14 '15 at 22:36
  • $\begingroup$ associationSplitBy[f_][as_Association] := SplitBy[Normal[as], f] // Map[Association]; - to wrap back up $\endgroup$ – alancalvitti Oct 14 '15 at 22:43

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.