The cut() Function In R: How To Use cut() In R

cut() function in r

The cut() function in R is a powerful tool to convert numeric values to factorial ranges. If you want to know more about this function then please check out our instructions below because we will show you its applications and some of the most common ways to apply it in our R program.

The cut() Function in R

What does the cut() function do in R?

The cut() function will convert numeric values into factorial ranges and show what ranges the values fall into. For example:

We have this vector x:

x <- c(32, 55, 12, 54, 23, 43, 11, 89, 21, 15)
x
[1] 32 55 12 54 23 43 11 89 21 15

And we want to “cut” this vector into 4 ranges. 

cut(x, breaks = 4)

Output:

[1] (30.5,50]   (50,69.5]   (10.9,30.5] (50,69.5]   (10.9,30.5] (30.5,50]   (10.9,30.5] (69.5,89.1]
[9] (10.9,30.5] (10.9,30.5]
Levels: (10.9,30.5] (30.5,50] (50,69.5] (69.5,89.1]

As you can see, the values have been divided into 4 ranges, and we can also see which range each value falls into. 

Syntax:

cut(vector, breaks,...)

Parameters:

  • vector: the numeric vector that will be cut.
  • breaks: can be a vector or a number representing the numbers of intervals.

How to use cut() in R?

With the given number of intervals

If we know the number of intervals that we want to cut the vector into, we can set the breaks value with an integer value.  

Example 2:

x <- 1:20
cut(x, breaks = 4)

Output:

[1] (0.981,5.75] (0.981,5.75] (0.981,5.75] (0.981,5.75] (0.981,5.75] (5.75,10.5]  (5.75,10.5] 
[8] (5.75,10.5]  (5.75,10.5]  (5.75,10.5]  (10.5,15.2]  (10.5,15.2]  (10.5,15.2]  (10.5,15.2] 
[15] (10.5,15.2]  (15.2,20]    (15.2,20]    (15.2,20]    (15.2,20]    (15.2,20]   
Levels: (0.981,5.75] (5.75,10.5] (10.5,15.2] (15.2,20]

Now let’s see how to read this output. The Levels line shows the ranges that the cut() function has created. As you can see, the first interval is from 0.981 to 5.75. The reason why it starts from 0.981 is so that we can get the 1 value. The other lines show which ranges each value falls into> For example: '1', '2', '3', '4', '5' falls into (0.981,5.75].

With specified intervals

We can also specify the intervals in the breaks argument. For example:

x <- 11:20
cut(x, breaks = c(10, 15, 20))

Output:

[1] (10,15] (10,15] (10,15] (10,15] (10,15] (15,20] (15,20] (15,20] (15,20] (15,20]
Levels: (10,15] (15,20]

Summary

In this tutorial, we have shown you what the cut() function in R is and how to apply it into our program. The idea of the cut() function is to divide numeric values into different intervals. We can use both the number of intervals or specified intervals for the breaks arguments.

Maybe you are interested:

Posted in R

Leave a Reply

Your email address will not be published. Required fields are marked *