Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-ordering this dataframe?

Tags:

dataframe

r

I read some txt file in R. For some reasons, the order of the text has been changed. Now, I want to re-order the dataframe. It will surely be silly but I got stuck on this and I can't find what I need on previous answers.

Let's take this example, I have the following situation:

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

The first column needs to be re-ordered and the second column (just text) needs to follow the reordering in the first column. This is what I would like to get.

    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

Thanks a lot for your help.

like image 500
Rollo99 Avatar asked Jun 07 '26 07:06

Rollo99


2 Answers

In Base:

df[order(df$doc_id),]
like image 97
SmokeyShakers Avatar answered Jun 10 '26 05:06

SmokeyShakers


We can use arrange

library(dplyr)
df %>%
    arrange(doc_id)
like image 40
akrun Avatar answered Jun 10 '26 03:06

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!