0

I want to re-order my dataframe according to a special list. For example,

t1 <- c(0,0,1,0,0)
t2 <- c(1,1,1,1,1)
t3 <- c(1,2,3,4,5)
b <- c("a","b","c","d","e")
df <-data.frame(t1,t2,t3)
rownames(df) <- b
> df
  t1 t2 t3
a  0  1  1
b  0  1  2
c  1  1  3
d  0  1  4
e  0  1  5
list <- c("b","c","a","e","d")
#I want to order the rows follow the order of "list", ideal result is 
  t1 t2 t3
b  0  1  2
c  1  1  3
a  0  1  1
e  0  1  5
d  0  1  4

How can I do that? Thank you in advance :)

Codezy
  • 662
  • 5
  • 17
  • Possible duplicate of [Order data frame rows according to vector with specific order](https://stackoverflow.com/questions/11977102/order-data-frame-rows-according-to-vector-with-specific-order) – Ankur Sinha Jun 05 '18 at 15:41

2 Answers2

2

We can use the 'list' (here it is a vector) as row names to order based on it (assuming that the 'list' and the row names of the 'df' are the same length and have the same values)

df[list,]
#  t1 t2 t3
#b  0  1  2
#c  1  1  3
#a  0  1  1
#e  0  1  5
#d  0  1  4
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can simply make b a factor column in the dataframe

t1 <- c(0,0,1,0,0)
t2 <- c(1,1,1,1,1)
t3 <- c(1,2,3,4,5)
b <- c("a","b","c","d","e")
df <-data.frame(t1,t2,t3, b =factor(x = b, levels = c("b","c","a","e","d")))
rownames(df) <- b

reorder:

> df[order(df$b),]
  t1 t2 t3 b
b  0  1  2 b
c  1  1  3 c
a  0  1  1 a
e  0  1  5 e
d  0  1  4 d
user5359531
  • 3,217
  • 6
  • 30
  • 55