简体   繁体   中英

How to order a dataframe by a column, first placing certain value in a column to de beginning and the rest in alphabetical order

I have this dataframe

a <- c("a", "f", "n", "c", "d")
b <- c("L", "S", "N", "R", "S")
df <- data.frame(a,b)
  a b
1 a L
2 f S
3 n N
4 c R
5 d S

Then I want the rows be ordered by column b, but first setting at the beginning the rows with "S" value and then alphabetically:

  a b
2 f S
5 d S
1 a L
3 n N
4 c R




You can exchange the S to a space during order .

df[order(sub("S", " ", df$b)), ]
#df[order(chartr("S", " ", df$b)), ] #Alternative
#  a b
#2 f S
#5 d S
#1 a L
#3 n N
#4 c R

Here is one option using factor .

df[order(factor(df$b, unique(c('S', sort(df$b))))), ]

#  a b
#2 f S
#5 d S
#1 a L
#3 n N
#4 c R

Using dplyr

library(dplyr)
df %>% 
   arrange(b != 'S', b)
  a b
1 f S
2 d S
3 a L
4 n N
5 c R

Or in base R

df[order(df$b != "S", df$b),]
  a b
2 f S
5 d S
1 a L
3 n N
4 c R

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