当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 cut()用法及代码示例


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

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

参数:
x:数字向量
break:向量的断点
labels:级别标签
包括.最低:包含最低中断值的布尔值
right:布尔值关闭右侧的区间
挖掘实验室:未提供标签时使用

范例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 



相关用法


注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Divide a Vector into Ranges in R Programming – cut() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。