R语言实战-数据类型3-因子(factor)

时间:2022-09-08 18:47:35

因子(factor)demo2-3.R

数据的类型分为名义型、有序型和连续型

其中名义型和有序型被称为因子

1 > weekdays<-c('Sunday','Monday','February','Wednesday','Thursday','Friday','Saturday')
2 > weekdays
3 [1] "Sunday"    "Monday"    "February"  "Wednesday" "Thursday"  "Friday"    "Saturday" 
4 > weekdays<-factor(weekdays)
5 > weekdays
6 [1] Sunday    Monday    February  Wednesday Thursday  Friday    Saturday 
7 Levels: February Friday Monday Saturday Sunday Thursday Wednesday
8 > #默认因子排序是按照字符排序

可以自己指定因子的顺序

1 > weekdays<-factor(
2 +   weekdays,
3 +   ordered = T,                 
4 +   levels = c('Sunday','Monday','February','Wednesday','Thursday','Friday','Saturday'))
5 > weekdays
6 [1] Sunday    Monday    February  Wednesday Thursday  Friday    Saturday 
7 Levels: Sunday < Monday < February < Wednesday < Thursday < Friday < Saturday