简体   繁体   中英

R: Sort a data frame based on the order of a vector?

Here is my example dataframe

df <- data.frame(id=rep(c(123,456),each=5),col1=c(3,6,4,3,8,9,2,1,3,4),col2=c(7,8,5,4,6,8,7,5,8,3))

    id col1 col2
1  123    3    7
2  123    6    8
3  123    4    5
4  123    3    4
5  123    8    6
6  456    9    8
7  456    2    7
8  456    1    5
9  456    3    8
10 456    4    3

desiredOrder <- rep(c(456,123),each=5)

And I want to sort according to the order specified in a particular vector (desiredOrder), so that the output looks like this:

    id col1 col2
1  456    9    8
2  456    2    7
3  456    1    5
4  456    3    8
5 456    4    3
6  123    3    7
7  123    6    8
8  123    4    5
9  123    3    4
10  123    8    6

(so the rows where id=456 got moved up above the rows where id=123, but the original order of the rows are preserved)

I have tried:

df[match(df$id,desiredOrder),] 

However the outcome is quite far from what I'm after:

     id col1 col2
6   456    9    8
6.1 456    9    8
6.2 456    9    8
6.3 456    9    8
6.4 456    9    8
1   123    3    7
1.1 123    3    7
1.2 123    3    7
1.3 123    3    7
1.4 123    3    7

We can convert the 'id' column to factor with levels specified as the unique elements in the vector and then do the order

df[order(factor(df$id, levels=unique(desiredOrder))),]
#    id col1 col2
#6  456    9    8
#7  456    2    7
#8  456    1    5
#9  456    3    8
#10 456    4    3
#1  123    3    7
#2  123    6    8
#3  123    4    5
#4  123    3    4
#5  123    8    6

You can also do this:

library(dplyr)

data_frame(id = desiredOrder) %>%
  distinct %>%
  left_join(df)

You can also use arrange() and desc() functions of dplyr library:

library(dplyr)
arrange(df, desc(id))

    id col1 col2
1  456    9    8
2  456    2    7
3  456    1    5
4  456    3    8
5  456    4    3
6  123    3    7
7  123    6    8
8  123    4    5
9  123    3    4
10 123    8    6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM