7
$\begingroup$

I would like to transform a table like

{<|"a" -> 1, "b" -> 11, "c" -> 111|>, <|"a" -> 1, "b" -> 12, "c" -> 112|>, <|"a" -> 2, "b" -> 22, "c" -> 111|>}

into an association that has the same keys and as values a list of the values in the original association, i.e.

{<|"a" -> {1, 1, 2}, "b" -> {11, 12, 22}, "c" -> {111, 112, 111}|>}

The way I did that was via

keys = Keys[as[[1]]]
values  = Lookup[as, #] & /@ keys
AssociationThread[keys -> values]

Two questions:

  • Is there a more straightforward way?

  • if everything is wrapped in a Dataset, how can I do it (without reverting to Normal)?

$\endgroup$

1 Answer 1

10
$\begingroup$
as={<|"a" -> 1, "b" -> 11, "c" -> 111|>, <|"a" -> 1, "b" -> 12, "c" -> 112|>, <|"a" -> 2, "b" -> 22, "c" -> 111|>};

Merge[as, Identity]

(*<|"a" -> {1, 1, 2}, "b" -> {11, 12, 22}, "c" -> {111, 112, 111}|>*)
$\endgroup$
3
  • 2
    $\begingroup$ +1. For the second question... if we are given ds = Dataset @ as, then we can use ds[Merge[Identity]]. $\endgroup$
    – WReach
    Jan 11, 2015 at 1:06
  • $\begingroup$ @Algohi Identity seems very poorly documented - is it just acting as a placeholder in this case? $\endgroup$ Jan 12, 2015 at 10:22
  • $\begingroup$ Merge[expr,f], the function f is applied to lists of values that share the same key. Identity returns its argument. To understand that check this another solution: Merge[as, {#}[[1]] &]. And also check this: Identity[{1, 1, 2}] $\endgroup$ Jan 12, 2015 at 14:17

Your Answer

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

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