3
$\begingroup$

Consider a 2D array of Associations. MapThread is used to simultaneously supply it to some function with other args

assocs = Map[Association @@ Distribute[{"a", "b", "c"} -> RandomInteger[100], List] &,  comps,{2}];
Grid@assocs

MapThread[#1["a"] &, {assocs(*,otherArgs*)}, 2]

gives

MapThread::mptd: Object {{<|a->67,b->67,c->67|>},{<|a->57,b->57,c->57|>},{<|a->100,b->100,c->100|>},{<|a->58,b->58,c->58|>,<|a->50,b->50,c->50|>,<|a->72,b->72,c->72|>}} at position {2, 1} in MapThread[#1[a]&,{{{<|a->67,b->67,c->67|>},{<|a->57,b->57,c->57|>},{<|a->100,b->100,c->100|>},{<|a->58,b->58,c->58|>,<|a->50,b->50,c->50|>,<|a->72,b->72,c->72|>}}},2] has only 1 of required 2 dimensions.

Answer at MapThread with non-rectangular lists suggest that the non-rectangular strucure of the list is to be blamed. However, I am finding it difficult to implement the accepted and upvoted answer there

Function[Null, f[##], Listable] @@ A

given without any examples.

So how does one use MapThread at level 2 independent of rectangularity?

$\endgroup$

1 Answer 1

2
$\begingroup$

Transpose for a ragged list :

Flatten[assocs, {{2}, {1}}]
{{<|"a" -> 16, "b" -> 16, "c" -> 16|>, <|"a" -> 29, "b" -> 29, 
   "c" -> 29|>}, {<|"a" -> 82, "b" -> 82, "c" -> 82|>, <|"a" -> 0, 
   "b" -> 0, "c" -> 0|>}}

raggedMapThread[f_, expr_, level_Integer: 1] := 
 Apply[f, Flatten[expr, List /@ Range[2, level + 1]], {level}]


raggedMapThread[#1["a"] &, assocs, 1] // MatrixForm

Matrixform of raggedMapThread 1 is entered because internally the level is incremented by 1 in the function raggedMapThread.

All I did is create me a lst:

lst = {{{a, b}, {c, d}}, {{1, 2}, {3, 4}}};

and use it assocs as comps.

assocs = Map[
   Association @@ 
     Distribute[{"a", "b", "c"} -> RandomInteger[100], List] &, 
   lst, {2}];
Grid@assocs

assocs

Since the assocs of the question are not too ragged it is very easy.

I selected the most valuable solutions from the questions listed in the reference given in this question.

$\endgroup$

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.