【发布时间】: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
问题是第一个变量是有序的,但是当我print或View数据框时,它没有有序,从上面可以看到。
关于class 和levels,一切看起来都很好:
> class(sch.rate)
[1] "data.frame"
> class(sch.rate$Level)
[1] "ordered" "factor"
> levels(sch.rate$Level)
[1] "Preschool" "Primary" "Secondary" "Higher"
当我将变量转换为有序因子时,我没有收到任何错误消息(如果出现任何问题,我想我会在查询变量的 class 和 levels 时看到它)。我使用了以下代码:
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.a、sch.b 和sch.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)
这一切的结果就是你在文章开头看到的。
【问题讨论】:
-
您使用什么语言工作?什么框架(如果有的话)?请编辑您的问题以添加相关标签。也请花点时间阅读the help pages、take the SO tour 和read about how to ask good questions。