Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R min() and max() Functions - Calculating Minimum and Maximum

R min() and max() Functions - Calculating Minimum and Maximum

R Language Examples R Language Examples

The R min() and max() functions are used to calculate the minimum and maximum values of elements in a vector, respectively.

These two functions are very commonly used in data exploration and outlier detection.

The syntax of the min() and max() functions is as follows:

min(x, na.rm = FALSE)

max(x, na.rm = FALSE)

Parameter Description:

Example

Create a vector

x

<-

c

(

12

,

27

,

3

,

4.2

,

2

,

2

,

54

,

21

,

4

,

2

)

Calculate the minimum

result.

min

<-

min

(

x

)

print

(

result.

min

)

Calculate the maximum

result.

max

<-

max

(

x

)

print

(

result.

max

)

The output of the code above is:

[1] -21

[1] 54

If you want to find the maximum or minimum among multiple vectors, you can use pmax() and pmin() for element-wise comparison:

Example

Two vectors

a

<-

c

(

10

,

20

,

30

)

b

<-

c

(

5

,

25

,

35

)

Find the maximum of all elements

print

(

max

(

a, b

)

)

Take the larger value at each position

print

(

pmax

(

a, b

)

)

Take the smaller value at each position

print

(

pmin

(

a, b

)

)

The output of the code above is:

[1] 35

[1] 10 25 35

[1]  5 20 30

R Language Examples R Language Examples