如何在R中使用setorder函数

时间:2015-04-24 12:56:49

标签: r data.table

我有一个模拟数据集:

d1 = structure(
  list(
    chan1 = c(1.49955768204777, 1.57924608282282, 
              1.62079872172079, 1.49955768204777,
              1.50897108417039, 1.47897959168283),
    chan2 = c(3.71459266186863, 3.71459266186863,
              3.66763591782946, 3.67359273988532,
              3.66408366995924, 3.68083665073346),
    chan3 = c(8.32529316285155, 6.30229174858652,
              6.97551768293611, 6.52653674461786,
              6.52653674461786, 6.07823977152575),
    chan4 = c(11.023719681933, 11.023719681933, 
              11.023719681933, 11.4613297390623,
              11.4613297390623, 11.5813471428122),
    chan5 = c(7.32862391337389, 7.38103675023449,
              7.81796038841145, 7.4216715642288,
              7.51924428352424, 7.35498863975821),
    rowname = c(2042051, 1454646, 289170,
                3307469, 3890829, 1741489),
    total_conv = c(359.161333500186, 359.161312264452,
                   359.16130836516, 359.161294408793,
                   359.161289598969, 359.161209958641),
    sum = c(31.8917871020749, 30.0008869254455, 
            31.1056323928309, 30.5826884698421,
            30.6801655213341, 30.1743917965125)
  ),
  .Names = c("chan1", "chan2", "chan3", "chan4", "chan5",
             "rowname", "total_conv", "sum"),
  class = "data.frame",
  row.names = c(NA, -6L)
)

现在我需要按 total_conv sum 变量对此数据集进行排序。 这里total_conv应按降序排序,并按升序排列。

当我使用以下功能时,我无法以所需格式对数据集进行排序。

d1<-setorder(as.data.table(d1),-total_conv,sum)

我如何克服这个问题?

1 个答案:

答案 0 :(得分:2)

您也可以尝试使用order代替setorder

setDT(d1)[order(-total_conv, sum)]

首先按降序total_conv然后降序sum进行排序。