7

是否可以重新排序数据帧的列,这是 dcast() 调用 Ex 的结果

给定数据:

> 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),但它仍然不起作用。有什么建议么?

4

2 回答 2

13

您可以使用factor()内部dcast()设置适当的级别顺序。

 dcast(copyOfRes, 
   docName ~ factor(week_number,levels=unique(week_number)), length)
      docName 11 2
    1    doc1 10 0
    2    doc2  1 1
于 2013-03-12T19:21:43.653 回答
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
于 2013-03-12T19:21:54.093 回答