Generic Person Generic Person - 11 months ago 50
R Question

vectorialized parallel max() and min()?

I have a

with columns "a" and "b". I want to add columns called "high" and "low" that contain the highest and the lowest among columns a and b.

Is there a way of doing this without looping over the lines in the dataframe?

edit: this is for OHLC data, and so the high and low column should contain the highest and lowest element between a and b on the same line, and not among the whole columns. sorry if this is badly worded.

Answer Source

Sounds like you're looking for pmax and pmin ("parallel" max/min):

Extremes                 package:base                  R Documentation

Maxima and Minima


     Returns the (parallel) maxima and minima of the input values.


     max(..., na.rm = FALSE)
     min(..., na.rm = FALSE)

     pmax(..., na.rm = FALSE)
     pmin(..., na.rm = FALSE), na.rm = FALSE), na.rm = FALSE)


     ...: numeric or character arguments (see Note).

   na.rm: a logical indicating whether missing values should be


     ‘pmax’ and ‘pmin’ take one or more vectors (or matrices) as
     arguments and return a single vector giving the ‘parallel’ maxima
     (or minima) of the vectors.  The first element of the result is
     the maximum (minimum) of the first elements of all the arguments,
     the second element of the result is the maximum (minimum) of the
     second elements of all the arguments and so on.  Shorter inputs
     are recycled if necessary.  ‘attributes’ (such as ‘names’ or
     ‘dim’) are transferred from the first argument (if applicable).