首页 > 解决方案 > 如何重新排序这个数据框?

问题描述

我在 R 中阅读了一些 txt 文件。由于某些原因,文本的顺序已更改。现在,我想重新排序数据框。这肯定会很愚蠢,但我被困在这个问题上,在以前的答案中找不到我需要的东西。

举个例子,我有以下情况:

df <- data.frame(doc_id = c(3, 10, 7, 1, 5, 2, 8, 4, 6, 9), Text = c("Text Text", "Text Stackoverflow", "Text Nice", "Text", "Text Not Nice", "Text Help", "Text Great", "Text programming", "Text Bad", "Text Example"))


   doc_id               Text
1       3          Text Text
2      10 Text Stackoverflow
3       7          Text Nice
4       1               Text
5       5      Text Not Nice
6       2          Text Help
7       8         Text Great
8       4   Text programming
9       6           Text Bad
10      9       Text Example

第一列需要重新排序,第二列(只是文本)需要遵循第一列中的重新排序。这就是我想要得到的。

    doc_id               Text
1       1               Text
2       2          Text Help
3       3          Text Text
4       4   Text programming
5       5      Text Not Nice
6       6           Text Bad
7       7          Text Nice
8       8         Text Great
9       9       Text Example
10      10 Text Stackoverflow

非常感谢你的帮助。

标签: rdataframe

解决方案


我们可以用arrange

library(dplyr)
df %>%
    arrange(doc_id)

推荐阅读