打印或查看数据框时未按顺序显示的因素

factor not displayed as ordered when printing or viewing dataframe

我有以下数据框

print(sch.rate)

      Level  15-49 married before 15 y.o. (%) 20-49 married before 15 y.o. (%)
1    Higher                            17.94                            16.33
2 Preschool                            24.69                            24.69
3   Primary                            16.42                            15.02
4 Secondary                             8.60                             7.70
  20-49 married before 18 y.o. (%)
1                            33.15
2                            48.64
3                            45.34
4                            28.34

问题是第一个变量是有序的,但是当我 printView 数据帧时,它没有被排序,正如你从上面看到的那样。

关于 classlevels 的一切看起来都很好:

> class(sch.rate)
[1] "data.frame"

> class(sch.rate$Level)
[1] "ordered" "factor" 

> levels(sch.rate$Level)
[1] "Preschool" "Primary"   "Secondary" "Higher" 

当我将变量转换为有序因子时,我没有收到任何错误消息(如果有任何错误,我想我会在查询 classlevels 时看到它变量)。我使用了以下代码:

sch.rate$Level <- ordered(sch.rate$Level, levels = c("Preschool", 
"Primary", "Secondary", "Higher"))

我错过了什么?

非常感谢

马诺洛

编辑 1: 我没有使用任何特定的框架。数据框是使用 survey 包中的 svytable 创建的意外事件 table。我将 svytable 对象转换为数据框,然后使用 spread 将其从长更改为宽。

sch.a <- round(prop.table(svytable(~schooling+mar.uni.15, design = wm.svy), 1)*100, 2)
sch.a <- as.data.frame(sch.a)
sch.a <- spread(sch.a, key = mar.uni.15, value = Freq)

sch.b <- round(prop.table(svytable(~schooling+mar.uni.15, design = wm.svy.20), 1)*100, 2)
sch.b <- as.data.frame(sch.b)
sch.b <- spread(sch.b, key = mar.uni.15, value = Freq)

sch.c <- round(prop.table(svytable(~schooling+mar.uni.18, design = wm.svy.20), 1)*100, 2)
sch.c <- as.data.frame(sch.c)
sch.c <- spread(sch.c, key = mar.uni.18, value = Freq)

我从临时数据帧 sch.asch.bsch.c 中删除了不需要的列,重命名了行和列并合并了三个临时数据帧:

sch.a$No <- NULL
sch.b$No <- NULL
sch.c$No <- NULL

sch.a <- `colnames<-`(sch.a, c("Level", "15-49 married before 15 y.o. (%)"))
sch.b <- `colnames<-`(sch.b, c("Level", "20-49 married before 15 y.o. (%)"))
sch.c <- `colnames<-`(sch.c, c("Level", "20-49 married before 18 y.o. (%)"))

sch.rate <- merge(sch.a, sch.b)
sch.rate <- merge(sch.rate, sch.c)

所有这一切的结果就是您在 post.

开头所看到的

您的 Level 因素被订购并不自动意味着您的 data.frame 将被订购,您需要 'tell' 它才能被订购。不过,您可以根据 Level 中的级别顺序执行此操作。我认为下面的代码应该可以实现我认为你想要的

sch.rate <- sch.rate[order(sch.rate$Level),]