4
$\begingroup$

I have a list: {0, 1, 1, 1, 2, 2, 2, 6}. I want to replace all the elements that are greater than 1 with the integer 1. In other words, I want Mma to return the list {0,1,1,1,1,1,1,1,1}.

$\endgroup$
3
  • 2
    $\begingroup$ Unitize[data] or Clip[data], maybe? $\endgroup$
    – user1066
    Mar 31, 2020 at 15:57
  • 1
    $\begingroup$ lst = Table[RandomInteger[10], 10] Map[Min[#, 5] &, lst] 5 as an example. You should use 1. $\endgroup$
    – uC-Harry
    Mar 31, 2020 at 16:13
  • 1
    $\begingroup$ lst /. x_ /; x > 1 -> 1 $\endgroup$
    – Akku14
    Mar 31, 2020 at 19:12

2 Answers 2

3
$\begingroup$

I just googled "wolfram mathematica replace if". Based on the first link I was able to figure it out in a minute!

lst = {0, 1, 1, 1, 2, 2, 2, 6};
lst /. {x_?(# > 1 &) -> 1}
{0, 1, 1, 1, 1, 1, 1, 1}
$\endgroup$
5
$\begingroup$

Usual approach would be to use ReplaceAll:

list = {0, 1, 1, 1, 2, 2, 2, 6};
list/.{x_?(# > 1 &) -> 1}

A slick approach would be

Boole /@ GreaterEqualThan[1] /@ list

Or even

Map[Min[#, 1] &, list]

Faster approach would be to use:

Unitize[list]
Clip[list]

All of them would give you:

{0, 1, 1, 1, 1, 1, 1, 1}

I just ran list = Table[RandomInteger[10], 100000] and used Mr.Wizard's timeAvg function:

list /. {x_?(# > 1 &) -> 1} // timeAvg
Boole /@ GreaterEqualThan[1] /@ list // timeAvg
Map[Min[#, 1] &, l] // timeAvg
Unitize[l] // timeAvg
Clip[l] // timeAvg

0.0690836

0.0559747

0.00204779

0.000139352

0.00022492

$\endgroup$
2
  • 2
    $\begingroup$ Thank you, this is very helpful. $\endgroup$
    – geoffrey
    Mar 31, 2020 at 17:03
  • $\begingroup$ @geoffrey, glad that was helpful. $\endgroup$
    – exp ikx
    Mar 31, 2020 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.