是否可以重新排序数据帧的列,这是dcast()调用的结果 E.x。
鉴于数据:
> dput(copyOfRes)
structure(list(docName = c("doc2", "doc1", "doc1", "doc1", "doc1",
"doc1", "doc1", "doc1", "doc1", "doc1", "doc1", "doc2"), day_of_week = c(11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 2)), .Names = c("docName",
"week_number"), row.names = c(NA, -12L), class = "data.frame")
所以,当我使用dcast()时如下:
library(reshape2)
dcast(copyOfRes, docName ~ week_number, length)
结果是:
docName 2 11
1 doc1 0 10
2 doc2 1 1
我希望数据框的值week_number
递减,如下所示:
docName 11 2
1 doc1 10 0
2 doc2 1 1
我尝试过dcast(copyOfRes, docName ~ sort(week_number, decreasing= TRUE), length)
,但它仍然不起作用。有什么建议吗?
答案 0 :(得分:12)
您可以在factor()
内dcast()
设置适当的关卡顺序。
dcast(copyOfRes,
docName ~ factor(week_number,levels=unique(week_number)), length)
docName 11 2
1 doc1 10 0
2 doc2 1 1
答案 1 :(得分:6)
您可以reorder
使用rev
dcast(copyOfRes, docName ~ reorder(week_number,rev(week_number)), length)
Using week_number as value column: use value.var to override.
docName 11 2
1 doc1 10 0
2 doc2 1 1