Message Boards Message Boards

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

Creating a dataset with multiple keys?

Posted 2 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 2 years ago

In case it might be helpful, I'd also suggest that you look into Dataset. The form that you say you want (dt in your original question), is actually not particularly well suited to further queries, or at least not when compared to Dataset.

If we think of the "CourseX" as values for a property like "courseName", then we can do this (I'm using member from your original example)

courseSizeData = 
 Dataset[AssociationThread[{"courseName", "year", "studentCount"} -> #] & /@ member]

enter image description here

And now you can do queries, filters, and other manipulations against courseSizeData.

POSTED BY: Eric Rimbey
Posted 2 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

Group Abstract Group Abstract