1. 程式人生 > >2-5 R語言基礎 factor

2-5 R語言基礎 factor

#因子:分類資料
#有序和無序
#整數向量+標籤label
#Male/Female
#常用於lm(),glm()

> x <- factor(c("female","female","female","male"))
> y <- factor(c("female","female","female","male"),levels=c("male","female"))


> #table 對於當前的因子有一個整體的瞭解
> table(x)
x
female male
3 1


> #去掉因子的屬性,看因子的內容
> unclass(x)
[1] 1 1 1 2
attr(,"levels")
[1] "female" "male"


> unclass(y)
[1] 2 2 2 1
attr(,"levels")
[1] "male" "female"


> class(x)#仍是因子型別
[1] "factor"


> class(y)
[1] "factor"


> class(unclass(x))#去掉因子的屬性,因子變為了整型
[1] "integer"


> class(unclass(y))
[1] "integer"