Group Abstract Group Abstract

Message Boards Message Boards

0
|
4.1K Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Creating a dataset with multiple keys?

Posted 3 years ago

Dear all, I would like to create a dataset like the one below (dt). I tried to do something but it did not work.

dt = <|"Course1" -> {<|"year" -> 2020, "students" -> 55|>, <|
     "year" -> 2021, "students" -> 40|>}, 
  "Course2" -> {<|"year" -> 2020, "students" -> 22|>, <|
     "year" -> 2021, "students" -> 38|>}, 
  "Course3" -> {<|"year" -> 2020, "students" -> 68|>, <|
     "year" -> 2021, "students" -> 50|>}|>
(*This is the original list*)
member = {{"Course1", 2020, 
   55}, {"Course1", 2021, 40}, {"Course2", 2020, 22}, {"Course2", 
   2021, 38}, {"Course3", 2020, 68}, {"Course3", 2021, 50}}
(*I tried to do this*)
rw = {"Course1", "Course2", "Course3"}
cl = {"year", "students"}
v1 = {{2020, 55}, {2021, 40}, {2020, 22}, {2021, 38}, {2020, 
   68}, {2021, 50}}
dt = AssociationThread[
   rw -> # &[AssociationThread[cl -> #] & /@ v1]];
(*Unfortunately this approach does not work.*)

Do you have any suggestion? Thank you :)

POSTED BY: Dani O
2 Replies
Posted 3 years ago
POSTED BY: Eric Rimbey
Posted 3 years ago

Starting from member (your original list):

dt=GroupBy[member, First->Rest, Map[AssociationThread[{"year","students"}->#]&,#]&]

or even a little bit shorter using the operator form of Map

dt=GroupBy[member, First->Rest, Map[AssociationThread[{"year","students"}->#]&]]

return what you wanted:

<|Course1->{<|year->2020,students->55|>,<|year->2021,students->40|>},Course2->{<|year->2020,students->22|>,<|year->2021,students->38|>},Course3->{<|year->2020,students->68|>,<|year->2021,students->50|>}|> 

(To understand better how it works, look of course at the syntax and examples in the docs for GroupBy and also you can proceed step by step and see what is going : GroupBy[member, First], then GroupBy[member, First->Last], ...]

POSTED BY: Chris P
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard