按向量排序数据帧同时保留索引

时间:2015-06-08 01:34:55

标签: r sorting vector dataframe

假设我的数据框名为结果

  id nobs
1 25  463
2 26  586
3 27  338
4 28  475
5 29  711
6 30  932

和这个载体:

ord = c(30, 29, 28, 27, 26, 25)

现在我明白我可以根据矢量ord对数据帧进行排序:

result[match(ord, result$id),]

获得以下结果:

  id nobs
6 30  932
5 29  711
4 28  475
3 27  338
2 26  586
1 25  463

但是,正如您所看到的,行索引也已更改(6,5,4 ..)。我想像以前一样保留它们(1,2,3 ......)。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在获取新数据框后清除行名称:

res <- result[match(ord, result$id),]
row.names(res) <- NULL
res
#   id nobs
# 1 30  932
# 2 29  711
# 3 28  475
# 4 27  338
# 5 26  586
# 6 25  463