Divide a Vector into Ranges in R Programming – cut() Function

cut() function in R Language is used to divide a numeric vector into different ranges.

Syntax:
cut.default(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3)

Parameters:
x: Numeric Vector
break: break points of the vector
labels: labels for levels
include.lowest: Boolean value to include lowest break value
right: Boolean value to close interval on the right
dig.lab: Used when labels are not provided

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to divide vector into ranges
  
# Generating a vector with random numbers 
y <- rnorm(100
    
# the output factor is created by the division 
# of the range of variables into pi / 3*(-3:3) 
# 4 equal-length intervals 
table(cut(y, breaks = pi / 3*(-3:3))) 

chevron_right


Output:

(-3.14, -2.09] (-2.09, -1.05]     (-1.05, 0]      (0, 1.05]   (1.05, 2.09] 
            0            12            33            40            12 
  (2.09, 3.14] 
            2 

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to divide vector into ranges
  
# Creating vectors 
age <- c(40, 49, 48, 40, 67, 52, 53)   
salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220
gender <- c("male", "male", "transgender"
            "female", "male", "female", "transgender"
    
# Creating data frame named employee 
employee<- data.frame(age, salary, gender)   
    
# Creating a factor corresponding to age with labels 
wfact = cut(employee$age, 3, labels = c('Young', 'Medium', 'Aged')) 
table(wfact) 

chevron_right


Output:

wfact
 Young Medium   Aged 
     4      2      1 



My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.