📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

Minima and Maxima

There is quite a difference between min() and pmin(). The former min() function simply combines all its arguments into one long vector and returns the minimum value in that vector. In contrast, if pmin() is applied to two or more vectors, it returns a vector of the pair-wise minima, hence the name pmin.

The max() and pmax() functions work similarly to the min() and pmin() functions.

Example: In case of vectors

> x <- c(12, 9, 23)
> y <- c(4, 13, 44)

> print(min(x, y))
[1] 4

> print(max(x, y))
[1] 44

> print(pmin(x, y))
[1]  4  9 23

> print(pmax(x, y))
[1] 12 13 44

Example: In case of Matrix

> z <- matrix(c(1, 5, 6, 2, 3, 2), nrow = 3, ncol = 2)
> print(z)
     [,1] [,2]
[1,]    1    2
[2,]    5    3
[3,]    6    2

> print(min(z))
[1] 1

> print(min(z[, 1], z[, 2]))
[1] 1

> print(pmin(z[, 1], z[, 2]))
[1] 1 3 2

> print(pmax(z[, 1], z[, 2]))
[1] 2 5 6

In the above example, min() computed the smallest value in (1, 5, 6, 2, 3, 2). But the call to pmin() computed the smaller of 1 and 2, yielding 1; then the smaller of 5 and 3, which is 3; then finally the minimum of 6 and 2, giving 2. Thus, the call returned the vector (1, 3, 2).