如何根据名称列表订购数据框?

时间:2018-06-05 15:32:45

标签: r 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)
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

我该怎么做?提前谢谢你:)

2 个答案:

答案 0 :(得分:2)

我们可以使用&#39;列表&#39; (这里是一个vector)作为基于它的行名称(假设&#39;列表&#39;以及&#39; df&#39;的行名称是相同的长度和具有相同的值)

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

答案 1 :(得分:1)

您只需在数据框

中设置b因子列即可
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

重排序:

> 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