how do I multiply list elements by a constant if the element satisfies a condition
(1 - UnitStep[# - .5]) # + 5 UnitStep[# - .5] # &@list
or
# (5 UnitStep[# - .5] /. 0 -> 1) &@list
or
If[# > .5, 5 #, #] & /@ list
{-1, 0, 5, 10, 15}
Using Replace
with a level spec works as well:
Replace[list, n_ /; 0.5 < n :> 5*n, {1}]
(* {-1, 0, 5, 10, 15} *)
Here, {1}
means that you try to replace each expression at level $1$ (and only level $1$) for replacement, and :>
is syntactic sugar for RuleDelayed
, which means the right hand side (5 * n
) is only evaluated after the pattern on the left hand side (n_ /; 0.5
) matches, and is evaluated each time it matches.
Function[x, If[x > 0.5, 5 x, x], Listable][list]
(* {-1, 0, 5, 10, 15} *)