我在 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
Run Code Online (Sandbox Code Playgroud)
第一列需要重新排序,第二列(只是文本)需要遵循第一列中的重新排序。这就是我想要得到的。
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
Run Code Online (Sandbox Code Playgroud)
非常感谢你的帮助。
其他答案非常好,但由于我经常处理大量数据,我想建议setorder()data.table 包中的函数。如果您曾经处理过一些巨大的数据框/数据表,您会发现它很有用。setorder()应该比基本版本和 dplyr 快。
例子:
library(data.table)
df <- setorder(df, doc_id)
Run Code Online (Sandbox Code Playgroud)