您的位置:首页 > 其它

R语言入门--R中的factor

2017-07-19 10:12 127 查看
如果学过Java或其他高级语言,应该有枚举类型这个概念,个人理解,R中的factor类似于这个枚举类型,但又有不同,毕竟Java中的enum本质上是整数,可以当成整数使用,但R中的factor却不可以直接当整数来使用,例如不能对factor类型的数据进行大小比较。但是可以进行等于或不等于的比较。

如果要进行大小比较,可以把factor类型的数据转换为字符型或数字型再比较。

(1) 创建factor

>mycolor<-factor(c("R","G","G","R","B"),levels =c("R","G","B"),labels=c("RED","GREEN","BLUE"))

> mycolor

[1] RED   GREEN GREEN RED   BLUE 

Levels: RED GREEN BLUE

> groupId<-factor(sample(1:3,10,rep=T))

> groupId

 [1] 3 3 3 2 2 3 2 2 1 2

Levels: 1 2 3

(2)等于或不等于的比较

> mycolor[mycolor=='GREEN']

[1] GREEN GREEN

Levels: RED GREEN BLUE

> mycolor[mycolor!="GREEN"]

[1] RED  RED  BLUE

Levels: RED GREEN BLUE

> groupId[groupId==3]

[1] 3 3 3 3

Levels: 1 2 3

(3) 大小比较

> groupId[groupId<3]

 [1] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>

Levels: 1 2 3

Warning message:

In Ops.factor(groupId, 3) : ‘<’ not meaningful for factors

转换类型后比较:

> groupId[as.numeric(groupId)<3]

[1] 2 2 2 2 1 2

Levels: 1 2 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: