Codezy
Codezy

Reputation: 662

How to order a dataframe according to a list of name?

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 :)

Upvotes: 0

Views: 53

Answers (2)

user5359531
user5359531

Reputation: 3555

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

Upvotes: 1

akrun
akrun

Reputation: 887118

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

Upvotes: 2

Related Questions