📜  在 R 编程中将向量划分为范围 - cut()函数

📅  最后修改于: 2022-05-13 01:54:36.944000             🧑  作者: Mango

在 R 编程中将向量划分为范围 - cut()函数

R 语言中的cut()函数用于将数值向量划分为不同的范围。

示例 1:

# 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))) 

输出:

(-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 

示例 2:

# 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) 

输出:

wfact
 Young Medium   Aged 
     4      2      1