Home > Back-end >  How to order a dataframe by a column, first placing certain value in a column to de beginning and th
How to order a dataframe by a column, first placing certain value in a column to de beginning and th

Time:10-06

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




CodePudding user response:

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

CodePudding user response:

You can remove the S during order.

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