I often find myself working with lists of lists of data, gathering data, performing computations, and producing a variety of different sorts of output. Intuitively, it seems like this should be done with nested Map
commands, but in practice that quickly becomes an unreadable mess, if I can get it to work at all. I typically end up switching the outer level(s) to a Table, which is more readable and avoids any potential problem with ambiguous Slot
s.
For clarity, consider the following trivial example. The following dataset describes a couple of grades at a hypothetical secondary school.
sampleStructure = {<|"grade" -> 11,
"students" -> {<|"name" -> "bill", "age" -> 15|>, <|
"name" -> "susan", "age" -> 16|>}|>, <|"grade" -> 12,
"students" -> {<|"name" -> "manuel", "age" -> 16|>, <|
"name" -> "morris", "age" -> 17|>, <|"name" -> "jackie",
"age" -> 16|>}|>};
Now we want to pass over the entire school, assigning a grade to every student. The process is designed to be perfectly objective and remove any chance of favoritism by the teacher -- if the student's age is an even number, he or she gets an A-, otherwise a B+.
I feel like there should be a very clean way to do this but in practice my code comes down to something like this:
Table[<|"grade" -> sampleStructure[[i, "grade"]],
"students" ->
Map[Append[#, <|"score" -> If[EvenQ[#[["age"]]], "A-", "B+"]|>] &,
sampleStructure[[i, "students"]]]|>, {i, 1,
Length[sampleStructure]}]
With more complex data structures, this gets ugly, and even with simple data it feels disproportionately complex. Is there a cleaner way to do this? Some kind of nested Map?
MapAt
? $\endgroup$