Programming, Code optimisation, R
There are many applications where one wishes to replace negative (or positive) elements of a vector (the method is applicable to both) with zeros. An example may be the computation of partial moments of a random variable. This Tip explains how this can be done in vectorised form.
How to do it
Assume one has a vector $x$ where one wishes to replace all negative elements by zero. The straightforward way in R would be
x[x<0] <- 0
However, this requires R to compute the logical vector $x < 0$, which is costly, especially for large vectors. The same can be achieved by the command
x <- (x + abs(x)) / 2
To replace positive values by 0, the computation is
x <- (x - abs(x)) / 2
Please note that if one intends to sum over the resulting vector (as is the case when one computes partial moments), one should of course first sum, then divide by 2.