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
如果要进行大小比较,可以把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
相关文章推荐
- 基础知识03 - 零基础入门学习汇编语言03
- GO语言入门到精通(二)Golang编译器搭建
- 28-语言入门-28-1的个数
- 寄存器(内存访问)02 - 零基础入门学习汇编语言14
- 外中断02 - 零基础入门学习汇编语言70
- go语言入门的资料
- R语言入门基础教程:常用运算函数
- 为什么选择python编程语言入门黑客攻防 给你几个理由!
- MQL4 语言入门。简单词组中的难题。
- 苹果Swift语言入门教程【中文版】
- linux操作系统下c语言编程入门
- [BX]和loop指令01 - 零基础入门学习汇编语言23
- [BX]和loop指令02 - 零基础入门学习汇编语言24
- ZZ:使用.NET语言开发Silverlight应用程序入门(一):了解项目结构
- JSTL 入门: 表达式语言
- Java语言入门 简述Java语言回收机制
- [BX]和loop指令04 - 零基础入门学习汇编语言26
- 慕课网——PHP入门篇(语言结构语句)
- 《程序设计入门—Java语言.翁恺》第七周编程作业(2)-完数
- [Java入门笔记] Java语言基础(二):常量、变量与数据类型