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}.
2 Answers
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}
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
-
2
-
Unitize[data]
orClip[data]
, maybe? $\endgroup$lst /. x_ /; x > 1 -> 1
$\endgroup$