當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。