4
$\begingroup$

Noob here.

I want to change the value of all the keys "e", that meet my filter criteria ("c" and "d" are above or equal 20).

myAsc = {
   <|"a" -> 0, "b" -> 1, "c" -> 10, "d" -> 10, "e" -> 0|>,
   <|"a" -> 0, "b" -> 2, "c" -> 20, "d" -> 20, "e" -> 0|>,
   <|"a" -> 0, "b" -> 3, "c" -> 20, "d" -> 20, "e" -> 0|>,
   <|"a" -> 0, "b" -> 4, "c" -> 20, "d" -> 20, "e" -> 0|>,
   <|"a" -> 0, "b" -> 5, "c" -> 10, "d" -> 10, "e" -> 0|>
   };

With Cases, I filter the Associations I want:

Cases[myAsc, x_ /; x["c"] >= 20 && x["d"] >= 20]


{<|"a" -> 0, "b" -> 2, "c" -> 20, "d" -> 20, "e" -> 0|>,
 <|"a" -> 0, "b" -> 3, "c" -> 20, "d" -> 20, "e" -> 0|>,
 <|"a" -> 0, "b" -> 4, "c" -> 20, "d" -> 20, "e" -> 0|>}

And so far I understand that I can use ReplacePart to change a value of "e" inside my list of Association.

ReplacePart[myAsc, {2, "e"} -> 1]
{<|"a" -> 0, "b" -> 1, "c" -> 10, "d" -> 10, "e" -> 0|>, 
 <|"a" -> 0, "b" -> 2, "c" -> 20, "d" -> 20, "e" -> 1|>, 
 <|"a" -> 0, "b" -> 3, "c" -> 20, "d" -> 20, "e" -> 0|>,
 <|"a" -> 0, "b" -> 4, "c" -> 20, "d" -> 20, "e" -> 0|>,
 <|"a" -> 0, "b" -> 5, "c" -> 10, "d" -> 10, "e" -> 0|>}

How can I combine this and change all values of "e" that met the filter criteria at once.

My desired output would be:

{<|"a" -> 0, "b" -> 1, "c" -> 10, "d" -> 10, "e" -> 0|>, 
 <|"a" -> 0, "b" -> 2, "c" -> 20, "d" -> 20, "e" -> 1|>, 
 <|"a" -> 0, "b" -> 3, "c" -> 20, "d" -> 20, "e" -> 1|>,
 <|"a" -> 0, "b" -> 4, "c" -> 20, "d" -> 20, "e" -> 1|>,
 <|"a" -> 0, "b" -> 5, "c" -> 10, "d" -> 10, "e" -> 0|>}

Thanks!

$\endgroup$

3 Answers 3

1
$\begingroup$
pos = Position[myAsc, x_ /; x["c"] >= 20 && x["d"] >= 20]

{{2}, {3}, {4}}

ReplacePart[myAsc, ({First@#, "e"} -> 1) & /@ pos]
{
  <|"a" -> 0, "b" -> 1, "c" -> 10, "d" -> 10, "e" -> 0|>
, <|"a" -> 0, "b" -> 2, "c" -> 20, "d" -> 20, "e" -> 1|
, <|"a" -> 0, "b" -> 3, "c" -> 20, "d" -> 20, "e" -> 1|
, <|"a" -> 0, "b" -> 4, "c" -> 20, "d" -> 20, "e" -> 1|>
, <|"a" -> 0, "b" -> 5, "c" -> 10, "d" -> 10, "e" -> 0|>
}
$\endgroup$
3
$\begingroup$
ReplaceAll[x_ /; x["c"] >= 20 && x["d"] >= 20 :> ReplacePart[x, "e" -> 1]] @ myAsc

enter image description here

$\endgroup$
3
$\begingroup$
myAsc // Map[<|#,"e"-> Boole[#["c"] >= 20 && #["d"] >= 20]|>&]
{Association["a" -> 0, "b" -> 1, "c" -> 10, "d" -> 10, "e" -> 0], 
Association["a" -> 0, "b" -> 2, "c" -> 20, "d" -> 20, "e" -> 1], 
Association["a" -> 0, "b" -> 3, "c" -> 20, "d" -> 20, "e" -> 1], 
Association["a" -> 0, "b" -> 4, "c" -> 20, "d" -> 20, "e" -> 1], 
Association["a" -> 0, "b" -> 5, "c" -> 10, "d" -> 10, "e" -> 0]}
$\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.