Replacing negative elements of a vector by 0


Enrico Schumann1


Programming, Code optimisation, R

Review Status



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.

Internal Links

Related Articles

External links

1. Gilli, M., D. Maringer and E. Schumann. (2011). Numerical Methods and Optimization in Finance. Elsevier.
2. R Development Core Team (2008). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License