R cut()

1 개요[ | ]

R cut()
  • "Convert Numeric To Factor → 숫자형를 팩터형으로 변환"
x <- seq(1,5,by=.5)
x
## [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
cut(x, breaks=2:4)
## [1] <NA>  <NA>  <NA>  (2,3] (2,3] (3,4] (3,4] <NA>  <NA> 
## Levels: (2,3] (3,4]
v <- runif(15, min=1, max=6 )
v
##  [1] 2.977400 1.490055 4.047673 5.943581 4.204432 3.393308 2.963403 1.075121
##  [9] 3.989742 4.164139 5.245737 2.687665 2.485356 2.418571 4.108471
cut(v, 3)
##  [1] (2.7,4.32]  (1.07,2.7]  (2.7,4.32]  (4.32,5.95] (2.7,4.32]  (2.7,4.32] 
##  [7] (2.7,4.32]  (1.07,2.7]  (2.7,4.32]  (2.7,4.32]  (4.32,5.95] (1.07,2.7] 
## [13] (1.07,2.7]  (1.07,2.7]  (2.7,4.32] 
cut(v, 3, labels=c("low","med","high"))
## Levels: (1.07,2.7] (2.7,4.32] (4.32,5.95]
##  [1] med  low  med  high med  med  med  low  med  med  high low  low  low  med 
cut(v, 3, labels=FALSE)
## Levels: low med high
##  [1] 2 1 2 3 2 2 2 1 2 2 3 1 1 1 2

2 예제[ | ]

df <- read.csv( header=T, stringsAsFactors=F, text="
student,math,science
Alice,100,50
Bob,90,60
Carol,80,70
David,70,80
Erin,60,90
")
df
##   student math science
## 1   Alice  100      50
## 2     Bob   90      60
## 3   Carol   80      70
## 4   David   70      80
## 5    Erin   60      90

df$math_grade <- cut(df$math, breaks=c(0,75,90,100))
df
##   student math science math_grade
## 1   Alice  100      50   (90,100]
## 2     Bob   90      60    (75,90]
## 3   Carol   80      70    (75,90]
## 4   David   70      80     (0,75]
## 5    Erin   60      90     (0,75]

df$math_grade <- cut(df$math, breaks=c(0,75,90,100), labels=c("C","B","A"))
df
##   student math science math_grade
## 1   Alice  100      50          A
## 2     Bob   90      60          B
## 3   Carol   80      70          B
## 4   David   70      80          C
## 5    Erin   60      90          C

3 같이 보기[ | ]

4 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}