cut Function in R (Example)
In this tutorial, I’ll explain how to convert numeric values to factorial ranges using the cut function in R.
The article contains one example for the application of cut. To be more precise, the content of the article looks as follows:
So let’s just jump right in…
Definition & Basic R Syntax of cut Function
Definition: The cut R function converts numeric values into factorial ranges.
Basic R Syntax: You can find the basic R programming syntax of the cut function below.
cut(my_values, my_breaks) # Basic R syntax of cut function
I’ll illustrate in the following an example how to apply the cut function in R.
Creating Exemplifying Data
Have a look at the following example data:
x <- 1:10 # Create example vector x # Print example vector # 1 2 3 4 5 6 7 8 9 10
The previous output of the RStudio console shows that our example data is a simple numeric vector ranging from 1 to 10.
Example: Applying cut Function in R
In this Example, I’ll show how to convert a numeric vector into a factor with certain ranges of values. Let’s assume that we want to convert our example vector to a factor with ranges from 0 to 4, 4 to 6, 6 to 7, and 7 to 10. Then, we can apply the cut function and the breaks argument of the cut function as shown below:
x_cut <- cut(x, breaks = c(0, 4, 6, 7, 10)) # Apply cut() x_cut # Print output # [1] (0,4] (0,4] (0,4] (0,4] (4,6] (4,6] (6,7] (7,10] (7,10] (7,10] # Levels: (0,4] (4,6] (6,7] (7,10]
As you can see based on the previous output of the RStudio console, we created a factor with four factor levels representing the previously specified ranges.
Video & Further Resources
I have recently published a video tutorial on the Statistics Globe YouTube channel, which explains the R programming syntax of this tutorial. You can find the video below:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, I can recommend reading the other articles of my website:
- Convert Character to Factor
- Convert Factor to Numeric
- Convert Data Frame Column to Numeric
- Data Type Conversion in R Programming
- R Functions List (+ Examples)
- The R Programming Language
In this R tutorial you learned how to apply the cut function to divide the range of a vector into intervals. Let me know in the comments below, in case you have further comments or questions.
Statistics Globe Newsletter