首页 > 解决方案 > 如何根据名称列表对数据框进行排序?

问题描述

我想根据特殊列表重新排序我的数据框。例如,

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

我怎样才能做到这一点?先感谢您 :)

标签: rdataframe

解决方案


我们可以使用'list'(这里是a vector)作为行名来根据它排序(假设'list'和'df'的行名长度相同并且具有相同的值)

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

推荐阅读