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

时间:2018-04-03 11:45:53

标签: r survey unordered

我有以下数据框

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: 我没有使用任何特定的框架。数据框是一个列联表,它是使用svytable包中的survey创建的。我将svytable对象转换为数据框,然后使用spread将其从long更改为wide。

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)

所有这一切的结果都是你在帖子开头看到的。

1 个答案:

答案 0 :(得分:0)

您订购的Level因素并不自动意味着您的data.frame将被订购,您需要告诉&#39;它要订购。您可以根据Level中的级别顺序执行此操作。我认为以下代码应该达到我想要的目标

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