Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order/sort data frame with respect to a character reference list

Tags:

dataframe

r

Consider these two df examples

df1=data.frame(names=c('a','b','c'),value=1:3)
df2=data.frame(names=c('c','a','b'),value=1:3)

so that

> df1
  names value
1     a     1
2     b     2
3     c     3
> df2
  names value
1     c     1
2     a     2
3     b     3

Now, I would like to sort the df1 to the same order as the names column in df2, to obtain

names value
c     3
a     1
b     2

How can I achieve this?

like image 798
Sukhi Avatar asked Sep 14 '25 09:09

Sukhi


1 Answers

try

df1[match(df2$names,df1$names),]

> df1[match(df2$names,df1$names),]
  names value
3     c     3
1     a     1
2     b     2
like image 159
shhhhimhuntingrabbits Avatar answered Sep 17 '25 01:09

shhhhimhuntingrabbits