版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lovely_J/article/details/82050110
factor(x = character(), levels, labels = levels,
exclude = NA, ordered = is.ordered(x), nmax = NA)
levels : 用来指定因子可能的级别(缺省值是向量x中互异的值)
labels:用来指定级别的名字
exclude:指定从向量x中剔除的级别值
ordered是一个逻辑型选项用来指定因子的级别是否有次序,回想数值型或字符型的x
> a <- factor(c('A','B','C','B','C','D'))
> a
[1] A B C B C D
Levels: A B C D
> b <- factor(c('D','C','B','B','A','D'))
> b
[1] D C B B A D
Levels: A B C D
#默认会把不重复的元素作为levels,而且默认字典序,可以通过设置levels来进行修改
#在设置labels的时候如果不指定对应的levels会按照默认的字典序levels顺序附上对应的label
> a <- factor(c('A','B','C','B','C','D'),labels=c('优','良','中','差'))
> a
[1] 优 良 中 良 中 差
Levels: 优 良 中 差
#这种labels的赋值方式,要求labels的个数和默认的levels个数相同
> b <- factor(c('A','C','B','B','C','D') ,labels=c('优','中','差'))
Error in factor(c("A", "C", "B", "B", "C", "D"), labels = c("优", "中", :
'labels'不对;长度3应该是一或4
> b
[1] D C B B A D
Levels: A B C D
#exclude去除A之后,A所在
> a <- factor(c('A','B','C','B','C','D'),exclude = 'A')
> a
[1] <NA> B C B C D
Levels: B C D
可以用来做数据的替换
> color <- factor(c('R','R','R','R','G','G','G','B','B','R','G','R','B','B','G','R','R'))
> color
[1] R R R R G G G B B R G R B B G R R
Levels: B G R> color <- factor(color,labels = c('Bule','Red','Green'))
> color
[1] Green Green Green Green Red Red Red Bule Bule Green Red Green
[13] Bule Bule Red Green Green
Levels: Bule Red Green
转换为向量,
> as.vector(color)
[1] "Green" "Green" "Green" "Green" "Red" "Red" "Red" "Bule" "Bule"
[10] "Green" "Red" "Green" "Bule" "Bule" "Red" "Green" "Green"
有序因子
> score1 <- c('A','B','C','B','C','A')
> score <- ordered(score1,levels = c('C','B','A'))
> score
[1] A B C B C A
Levels: C < B < A
> exam <- c(75,81,84,87,82,60,60,76,81,78,66,76,80,70,80,88,75,76,88,84,88,72,74,68,61,67,64,82,60,73)
> exam
[1] 75 81 84 87 82 60 60 76 81 78 66 76 80 70 80 88 75 76 88 84 88 72 74 68 61
[26] 67 64 82 60 73
> exam1 <- cut(exam,breaks = 3)
> exam1
[1] (69.3,78.7] (78.7,88] (78.7,88] (78.7,88] (78.7,88] (60,69.3]
[7] (60,69.3] (69.3,78.7] (78.7,88] (69.3,78.7] (60,69.3] (69.3,78.7]
[13] (78.7,88] (69.3,78.7] (78.7,88] (78.7,88] (69.3,78.7] (69.3,78.7]
[19] (78.7,88] (78.7,88] (78.7,88] (69.3,78.7] (69.3,78.7] (60,69.3]
[25] (60,69.3] (60,69.3] (60,69.3] (78.7,88] (60,69.3] (69.3,78.7]
Levels: (60,69.3] (69.3,78.7] (78.7,88]
> age <- c(12:17)
> age
[1] 12 13 14 15 16 17
> gender <- c('F','M','M','F','F','M')
> gender
[1] "F" "M" "M" "F" "F" "M"
> tapply (age,gender,mean)
F M
14.33333 14.66667