R语言里面的因子
R语言中的因子确实不好理解,很多人都这么觉得。在R语言中,因子(factor)表示的是一个符号、一个编号或者一个等级,即,一个点。例如,人的个数可以是1,2,3,4......那么因子就包括,1,2,3,4.....还有统计量的水平的时候用到的高、中、低,也是因子,因为他是一个点。与之区别的向量,是一个连续性的值,例如,数值中有1,1.1,1.2......可以作为数值来计算,而因子则不可以。如果用我自己的理解,简单通俗来讲:因子是一个点,向量是一个有方向的范围。在R中,如果把数字作为因子,那么在导入数据之后,需要将向量转换为因子(factor),而因子在整个计算过程中不再作为数值,而是一个"符号"而已。因子的水平就是因子的所有不相同的符号的集合。
创建因子的函数介绍如下:
factor(x, levels = sort(unique(x), na.last = TRUE), labels = levels, exclude = NA, ordered = is.ordered(x))
levels 用来指定因子可能的水平(缺省值是向量x中互异的值);labels
用来指定水平的名字;exclude表示从向量x中剔除的水平值;ordered是
一个逻辑型选项用来指定因子的水平是否有次序。回想数值型或字符型
的x。
> factor(1:3) [1] 1 2 3 Levels: 1 2 3 > factor(1:3, levels=1:5) [1] 1 2 3 Levels: 1 2 3 4 5 > factor(1:3, labels=c("A", "B", "C")) [1] A B C Levels: A B C > factor(1:5, exclude=4) [1] 1 2 3 NA 5 Levels: 1 2 3 5
函数levels用来提取一个因子中可能的水平值:
> f <- factor(c(2, 4), levels=2:5) > f [1] 2 4 Levels: 2 3 4 5 > levels(f) [1] "2" "3" "4" "5"
因子用来存储类别变量(categorical
variables)和有序变量,这类变量不能用来计算而只能用来分类或者计数。因子表示分类变量,有序因子表示有序变量。生成因子数据对象的函数是factor(),语法是factor(data,
levels, labels, ...),其中data是数据,levels是因子水平向量,labels是因子的标签向量。
1、创建一个因子。
例1:
>colour <- c('G', 'G', 'R', 'Y', 'G', 'Y', 'Y', 'R', 'Y') >col <- factor(colour) >col1 <- factor(colour, levels = c('G', 'R', 'Y'), labels = c('Green', 'Red', 'Yellow')) #labels的内容替换colour相应位置对应levels的内容 >col2 <- factor(colour, levels = c('G', 'R', 'Y'), labels = c('1', '2', '3')) >col_vec <- as.vector(col2) #转换成字符向量 >col_num <- as.numeric(col2) #转换成数字向量 >col3 <- factor(colour, levels = c('G', 'R'))
2、创建一个有序因子。
例1:
>score <- c('A', 'B', 'A', 'C', 'B') >score1 <- ordered(score, levels = c('C', 'B', 'A')); >score1 [1] A B A C B Levels: C < B < A
3、用cut()函数将一般的数据转换成因子或有序因子。
例1:
>exam <- c(98, 97, 52, 88, 85, 75, 97, 92, 77, 74, 70, 63, 97, 71, 98, 65, 79, 74, 58, 59, 60, 63, 87, 82, 95, 75, 79, 96, 50, 88) >exam1 <- cut(exam, breaks = 3) #切分成3组 >exam1 [1] (82,98] (82,98] (50,66] (82,98] (82,98] (66,82] (82,98] (82,98] (66,82] [10] (66,82] (66,82] (50,66] (82,98] (66,82] (82,98] (50,66] (66,82] (66,82] [19] (50,66] (50,66] (50,66] (50,66] (82,98] (66,82] (82,98] (66,82] (66,82] [28] (82,98] (50,66] (82,98] Levels: (50,66] (66,82] (82,98] >exam2 <- cut(exam, breaks = c(0, 59, 69, 79, 89, 100)) #切分成自己设置的组 > exam2 [1] (89,100] (89,100] (0,59] (79,89] (79,89] (69,79] (89,100] (89,100] [9] (69,79] (69,79] (69,79] (59,69] (89,100] (69,79] (89,100] (59,69] [17] (69,79] (69,79] (0,59] (0,59] (59,69] (59,69] (79,89] (79,89] [25] (89,100] (69,79] (69,79] (89,100] (0,59] (79,89] Levels: (0,59] (59,69] (69,79] (79,89] (89,100] >attr(exam1, 'levels'); [1] "(50,66]" "(66,82]" "(82,98]" >attr(exam2, 'levels'); [1] "(0,59]" "(59,69]" "(69,79]" "(79,89]" "(89,100]" >attr(exam2, 'class') [1] "factor" #一个有序因子 > x <- factor(rep(1:5,3)) > ordered(x,labels = c('a1','a2','a3','a4','a5')) [1] a1 a2 a3 a4 a5 a1 a2 a3 a4 a5 a1 a2 a3 a4 a5 Levels: a1 < a2 < a3 < a4 < a5
关于因子就说到这里,实际用的非常少!对于逻辑数据以后会遇到再说,就不专门讲了。
作者:柯广的网络日志
微信公众号:Java大数据与数据仓库