6
$\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$
1
  • $\begingroup$ SplitBy expects a List as the first argument, no? $\endgroup$
    – chuy
    Commented Oct 13, 2015 at 21:38

1 Answer 1

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$
4
  • $\begingroup$ Unfortunately that projects the keys out and there's no easy way to sync them to the processed list. $\endgroup$ Commented Oct 13, 2015 at 20:56
  • $\begingroup$ Thanks for the edit, composing with Last works. $\endgroup$ Commented Oct 13, 2015 at 21:17
  • $\begingroup$ Values also works in place of Last $\endgroup$ Commented Oct 14, 2015 at 22:36
  • $\begingroup$ associationSplitBy[f_][as_Association] := SplitBy[Normal[as], f] // Map[Association]; - to wrap back up $\endgroup$ Commented Oct 14, 2015 at 22:43

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.