根据给定的订单订购数据框

时间:2017-03-14 06:39:43

标签: r dataframe

可能是一个简单的问题。

我有data.frame(样本名称,因子级别和因子级别的复制品):

df <- data.frame(name=c("DP_A","DP_B","PA_A","PA_B","PA_C"),
                 level=c("DP","DP","PA","PA","PA"),
                 replicate=c("A","B","A","B","C"),
                 stringsAsFactors = F)

以及其列之一的给定所需顺序 - 因子级别:

level.order <- c("PA","DP")

所以我想按df(意为level.order)订购df$level

如果我可以加入level.order我可以按df$replicate订购,可以是character(如本例所示),integer,或它们的组合(例如,A1,A2等)

在这种情况下,有序的df将是:

df <- data.frame(name=c("PA_A","PA_B","PA_C","DP_A","DP_B"),
                 level=c("PA","PA","PA","DP","DP"),
                 replicate=c("A","B","C","A","B"),
                 stringsAsFactors = F)

1 个答案:

答案 0 :(得分:4)

有几种选择。一个是a [589, 273, 981, 642, 702, 883, 319, 128] b [(589, 0), (273, 1), (981, 2), (642, 3), (702, 4), (883, 5), (319, 6), (128, 7)] c [(128, 7), (273, 1), (319, 6), (589, 0), (642, 3), (702, 4), (883, 5), (981, 2)] d [7, 1, 6, 0, 3, 4, 5, 2] z [128, 273, 319, 589, 642, 702, 883, 981] y <zip object at 0x035E38A0> x [(7, 128), (1, 273), (6, 319), (0, 589), (3, 642), (4, 702), (5, 883), (2, 981)] w [(0, 589), (1, 273), (2, 981), (3, 642), (4, 702), (5, 883), (6, 319), (7, 128)] v [589, 273, 981, 642, 702, 883, 319, 128] u [589, 273, 981, 642, 702, 883, 319, 128] '级别'列,基于它match order`

level.order' to get the numeric index and then

或将“级别”转换为df[order(match(df$level, level.order)),] ,将factor指定为“level.order”,然后将levels指定为<{p}}

order