## Author

Enrico Schumann^{1}

## Keywords

Programming, Code optimisation, R

## Review Status

*Unreviewed*

# Motivation

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

Concepts |

… |

Tutorials |

Tips |

… |

Related Articles |

… |

# External links

References |

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. http://www.R-project.org. |

Weblinks |

… |