因子(factor)是R语言中比较特殊的一个数据类型, 它是一个用于存储类别的类型,举个例子,从性别上,可以把人分为:男人和女人,从年龄上划分,又可以把人分为:未成年人(<18岁),成年人(>=18)。R把表示分类的数据称为因子,因子的行为有时像字符串,有时像整数。因子是一个向量,通常情况下,每个元素都是字符类型,也有其他数据类型的元素。因子具有因子水平(Levels),用于限制因子的元素的取值范围,R强制:因子水平是字符类型,因子的元素只能从因子水平中取值,这意味着,因子的每个元素要么是因子水平中的字符(或转换为其他数据类型),要么是缺失值,这是因子的约束,是语法上的规则。

一,创建因子

通常情况下,在创建数据框变量时,R隐式把数据类型为字符的列创建为因子,这是因为R会把文本类型默认为类别数据,并自动转换为因子。

例如,创建一个数据框变量,通过class()函数检查gender列的类,结果是因子类型,而不是字符向量:

heights <- data.frame(
height_cm=c(,,),
gender=c('f','m','f')
)
> class(heights$gender)
[] "factor"

还可以通过factor()函数创建因子,factor()函数的第一个参数必须是字符向量,通过levels参数显式设置因子水平,

factor(x = character(), levels, labels = levels,
exclude = NA, ordered = is.ordered(x), nmax = NA)

参数注释:

  • x:是向量,通常是由少量唯一值的字符向量
  • levels:水平,字符类型,用于设置x可能包含的唯一值,默认值是x的所有唯一值。如果x不是字符向量,那么使用as.character(x)把x转换为字符向量,然后获取x向量的水平。x向量的取值跟levels有关。
  • labels:是水平的标签,字符类型,用于对水平添加标签,相当于对因子水平重命名;
  • exclude:排除的字符
  • ordered:逻辑值,用于指定水平是否有序;
  • nmax:水平的上限数量

例如,因子sex的值是向量c('f','m','f','f','m'),因子水平是c('f','m'):

> sex <- factor(c('f','m','f','f','m'),levels=c('f','m'))
> sex
[] f m f f m
Levels: f m

二,因子水平

因子水平规定了因子取值的范围,每一个因子,都包含因子水平的信息,例如,打印gender列,可以看到因子的元素和水平:

> heights$gender
[] f m f
Levels: f m

该因子中的每个值都是一个字符串,它们被限制为“f”、“m”和缺失值(NA)。如果把其他字符串添加到gender列中,R会抛出警告消息,并把错误赋值的元素设置为NA,例如:

> heights$gender[]<-"female"
Warning message:
In `[<-.factor`(`*tmp*`, , value = c(NA, 2L, 1L)) :
invalid factor level, NA generated

1,查看因子水平

因子水平,可以通过函数levels(factor)来查看:

> levels(heights$gender)
[] "f" "m"

水平的级数,相当于level的长度,可以由nlevels函数查询到:

> nlevels(heights$gender)
[]

2,因子水平的标签

使用factor函数创建因子,可以使用labels参数为每个因子水平添加标签,labels参数的字符顺序,要和levels参数的字符顺序保持一致,例如:

> sex=factor(c('f','m','f','f','m'),levels=c('f','m'),labels=c('female','male'),ordered=TRUE)
> sex
[] female male female female male
Levels: female < male

三,有序因子

通常情况下,因子一般是无序的,这可以通过is.ordered()函数来验证:

> is.ordered(sex)
[] FALSE

因子的顺序,实际上是指因子水平的顺序,有序因子的因子水平是有序的。在特殊情况下,有些因子的水平在语义上大于或小于其他水平,R支持按顺序排列的因子,使用ordered函数,或通过给factor函数传入order=TRUE参数,把无序因子转换为有序的因子。

1,通过ordered()函数把现有因子转换为有序因子

ordered()函数不能指定特定因子水平的顺序,通常情况下,因子中先出现的水平小于后出现的水平。

例如,通过ordered函数把sex因子转换为有序的因子:

> ordered(sex)
[] f m f f m
Levels: f < m

2,创建有序的因子

通过factor函数创建有序因子,通过levels指定因子的顺序。

> sex <- factor(c('f','m','f','f','m'),levels=c('f','m'),ordered=TRUE)
> sex
[] f m f f m
Levels: f < m

3,按照指定的顺序转换现有的因子

因子的顺序,其实是因子水平的顺序,我们可以通过levels,使现有的因子按照指定的因子水平来排序。

例如,把heights数据库框的gender,按照指定的levels,转换成有序因子:

heights$gender <- factor(heights$gender, levels=c('m','f'),ordered=TRUE)

四,删除因子水平

在数据清理时,可能需要去掉与因子水平对应的数据,通常情况下,需要删除未使用的因子水平,可以使用droplevels函数,它接受因子或是数据框作为参数。

## S3 method for class 'factor'
droplevels(x, exclude = if(anyNA(levels(x))) NULL else NA, ...)
## S3 method for class 'data.frame'
droplevels(x, except, exclude, ...)

如果x是数据框,那么把数据框中未使用的因子删除。

heights$gender <- droplevels(gender)

五,把因子水平转换为字符串

在数据清理中,有时需要把因子转换为字符,通常情况下,使用as.character()函数,把因子转换为字符串:

> as.character(heights$gender)
[] NA "m" "f"

或者使用其他类型转换函数,把因子转换为特定的数据类型。

六,把因子转换成相应的整数

使用as.numeric()或as.integer()函数可以把因子转换成对应的整数

> as.integer(sex)
[]

七,把连续变量分割为类别

函数cut()能够把数值变量切成不同的块,然后返回一个因子

cut(x, breaks, labels = NULL)

参数注释:

  • x:数值变量
  • breaks:切割点向量
  • labels:每一个分组的标签

例如,把身高数据,按照指定的切割点向量分割:

cut(heights$height_cm,c(,,))
[] (,] (,] (,]
Levels: (,] (,]

八,修改数据框中的因子

一般情况下,数据框中的字符类型的列会转换为因子类型,要修改因子类型,一般通过三步来完成:

mydata$Category <- as.character(mydata$Category)
mydata <- within(mydata,{Category[Category=="old name"] <- "new name"})
mydata$Category <- as.factor(mydata$Category)

当需要把因子转换为有序因子时,要注意因子水平的顺序,

mydata$Category <- as.factor(mydata$Category, levels=c('your ordered'), ordered=TRUE)

参考文档:

如何理解R中因子(factor)的概念?

查看 table,view,sp的定义的更多相关文章

  1. Table View Programming Guide for iOS---(二)----Table View Styles and Accessory Views

    Table View Styles and Accessory Views 表格视图的风格以及辅助视图 Table views come in distinctive styles that are ...

  2. Table View Programming Guide for iOS---(六)---A Closer Look at Table View Cells

    A Closer Look at Table View Cells A table view uses cell objects to draw its visible rows and then c ...

  3. MySQL 建表语句 create table 中的列定义

    MySQL 建表语句 create table 中的列定义: column_definition: data_type [NOT NULL | NULL] [DEFAULT default_value ...

  4. 制作一个可以滑动操作的 Table View Cell

    本文转载至 https://github.com/nixzhu/dev-blog Apple 通过 iOS 7 的邮件(Mail)应用介绍了一种新的用户界面方案——向左滑动以显示一个有着多个操作的菜单 ...

  5. Table View Programming Guide for iOS---(七)---Managing Selections

    Managing Selections 管理选择 When users tap a row of a table view, usually something happens as a result ...

  6. Table View Programming Guide for iOS---(五)---Creating and Configuring a Table View

    Creating and Configuring a Table View Your app must present a table view to users before it can mana ...

  7. Table View Programming Guide for iOS---(四)---Navigating a Data Hierarchy with Table Views

    Navigating a Data Hierarchy with Table Views 导航数据表视图层次 A common use of table views—and one to which ...

  8. Table View Programming Guide for iOS---(三)----Overview of the Table View API

    Overview of the Table View API 表格视图API概述 The table view programming interface includes several UIKit ...

  9. Table View Programming Guide for iOS---(一)---About Table Views in iOS Apps

    About Table Views in iOS Apps Table views are versatile user interface objects frequently found in i ...

随机推荐

  1. 《python核心编程》笔记——杂项

    python语句默认会给每一行添加一个换行符,只要在最后加一个逗号就能改变这种行为 若函数里没有return就自动返回None对象 PEP(python增强提案简称)http://python.org ...

  2. WEB响应布局

    [15/06月,15] em是相对长度单位.相对于当前对象内文本的字体尺寸.如当前对行内文本的字体尺寸未被人为设置,则相对于浏览器的默认字体尺寸.(引自CSS2.0手册) 任意浏览器的默认字体高都是1 ...

  3. JDBC Boilerplate

    public class Student{ private Integer studId; private String name; private String email; private Dat ...

  4. VS2012下配置OpenCV2.4.5

    最近在折腾了一下VS2012的OpenCVS2.4.5配置,同VS2010下基本相同,做个简单的记录,以备日后查阅. 1. 安装OpenCV 从OpenCV官网:http://opencv.org/下 ...

  5. 20145301&20145321&20145335实验三

    20145301&20145321&20145335实验三 这次实验我的组员为:20145301赵嘉鑫.20145321曾子誉.20145335郝昊 实验内容详见:实验三

  6. Runtime消息传送

    person.h #import<Foundation/Foundation.h> @interfacePerson :NSObject + (void)eat; - (void)run: ...

  7. CentOS7 bonding配置

    操作系统:CentOS Linux release 7.1.1503 (Core) 网卡适配器: eno1.eno2 bonding类型:mode=1 (active-backup),主-备份策略 网 ...

  8. vpn找不到设备,win7建立新的VPN总时显示错误711,无法启动 Remote Access Connection Manager 及 Remote Access Auto Connection Manager 错误1068

    试试相关服务!一.remote access connection manager是网络连接的服务,它依赖于Technology服务,现在你的这个服务已经启动,而Secure Socket Tunne ...

  9. Xamarin.Forms.Platform.Perspex, Xamarin Forms 的 Perspex(号称下一代WPF) 实现

    Perspex, 跨平台的UI框架,加上Xamarin Forms的跨平台的中间层,这样同一套代码就可跨几乎所有已知平台,这其中包括旧版Windows, Linux及Mac OS. 目前,基本控件可显 ...

  10. 【Win10 UWP】后台任务与动态磁贴

    动态磁贴(Live Tile)是WP系统的大亮点之一,一直以来受到广大用户的喜爱.这一讲主要研究如何在UWP应用里通过后台任务添加和使用动态磁贴功能. 从WP7到Win8,再到Win10 UWP,磁贴 ...