因子用于存储不同类别的数据类型,例如人的性别有男和女两个类别,年龄来分可以有未成年人和成年人。R 语言创建因子使用 factor() 函数,向量作为输入参数。
factor(x = character(), levels, labels = levels,
exclude = NA, ordered = is.ordered(x), nmax = NA)
levels:用来指定因子可能的水平(缺省值是向量x中互异的值)
labels:用来指定水平的名字
exclude:表示从向量x中剔除的水平值
x <- c("男", "女", "男", "男", "女")
class(x)
sex <- factor(x)
class(sex)
print(sex)
print(is.factor(sex))
a<- factor(c("A",'B','B','A','C','B','A','C'),labels= c("优","良","差"))
a<- factor(c('A','B','B','A','C','B','A','C',NA),labels= c("优","良","差"),exclude = NA)
a<- factor(c('A','B','B','A','D','C','B','A','C','D'),labels= c("优","良","差"),exclude = 'D')
score <- c('A','C','B','A','C','B','A')
a <- ordered(score)
class(a)
b <- factor(score,ordered=TRUE)
class(b)
a <- c(1:10)
b <- cut(a, breaks = 5)
class(b)
注:cut将x的范围划分为多个区间,并根据它们落下的区间对x中的值进行编码。最左边的间隔对应于一级,下一个最左边的间隔对应于二级,依此类推。
stringsAsFactors = FALSE
Name <- c("张三", "李四", "王五")
age <- c(21,21,31)
sex <- c("男", "女", "男")
# 注意区别
Mydata1 <- data.frame(Name, age, sex) # 默认 stringsAsFactors = FALSE
class(Mydata1$Name)
Mydata2 <- data.frame(Name, age, sex,stringsAsFactors = TRUE)
class(Mydata2$Name)