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

R range() Function - Computing the Numeric Range

R range() Function - Computing the Numeric Range

R Language Examples R Language Examples

The R range() function is used to return the minimum and maximum values of elements in a vector.

It returns a vector of two values at once, which is more convenient than calling min() and max() separately.

The syntax of the range() function is as follows:

range(x, na.rm = FALSE)

Parameter Description:

Example

Create a vector

x

<-

c

(

12

,

27

,

3

,

4.2

,

2

,

2

,

54

,

21

,

4

,

2

)

Compute the range

result.

range

<-

range

(

x

)

print

(

result.

range

)

Compute the span (maximum minus minimum)

print

(

diff

(

result.

range

)

)

The output of the code above is:

[1] -21  54

[1] 75

range() is especially useful when plotting, for setting the range of axes:

Example

Create data

x

<-

1

:

10

y

<-

c

(

3

,

7

,

2

,

9

,

15

,

8

,

12

,

5

,

18

,

10

)

View the range of y

y_range

<-

range

(

y

)

print

(

y_range

)

Use range to extend the axis range

plot

(

x, y, type

=

"o"

,

     ylim

=

c

(

y_range

[

1

]

1

, y_range

[

2

]

1

)

,

     main

=

"Line plot with range()"

)

The output of the code above is:

[1]  2 18

R Language Examples R Language Examples