简体   繁体   中英

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

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

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

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