【问题标题】:factor not displayed as ordered when printing or viewing dataframe [closed]打印或查看数据框时未按顺序显示因子[关闭]
【发布时间】:2018-04-03 11:45:52
【问题描述】:

我有以下数据框

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 创建的列联表。我将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)

这一切的结果就是你在文章开头看到的。

【问题讨论】:

标签: r survey unordered


【解决方案1】:

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

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

【讨论】:

  • 效果很好。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 2013-10-02
相关资源
最近更新 更多