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
相關用法
- R語言 as.vector()用法及代碼示例
- R語言 is.vector()用法及代碼示例
- R語言 split()用法及代碼示例
- R語言 as.factor()用法及代碼示例
- R語言 make.unique()用法及代碼示例
- R語言 charmatch()用法及代碼示例
- R語言 replace()用法及代碼示例
- R語言 substring()用法及代碼示例
- R語言 str_detect()用法及代碼示例
- R語言 seq()用法及代碼示例
- R語言 sort()用法及代碼示例
- R語言 range()用法及代碼示例
- R語言 diff()用法及代碼示例
- R語言 median()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi_biet大神的英文原創作品 Divide a Vector into Ranges in R Programming – cut() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。