How to get the row order in one data frame to match the row other in another data frame?

Viewed 50

I'm working with two data frames. I want the order of the rows one dataframe to match the orders of the rows in another dataframe.

For example:

terms_1 <- c("Cat", "Hat", "Dog", "Bat", "Mat", "Cow")
terms_2 <- c("Dog", "Cow", "Mat", "Cat", "Hat", "Bat")

terms_1_df <- data.frame(terms = terms_1, values = sample(seq(1,100, 1), replace = T, length(terms_1)))
terms_2_df <- data.frame(terms = terms_2, values = sample(seq(1,100, 1), replace = T, length(terms_2)))

> terms_1_df
  terms values
1   Cat     22
2   Hat     47
3   Dog     91
4   Bat     48
5   Mat     60
6   Cow     46
> terms_2_df
  terms values
1   Dog     94
2   Cow     35
3   Mat     68
4   Cat     21
5   Hat     67
6   Bat     60

I want the rows in terms_2_df rearranged to match the order of the terms rows in terms_1_df

Thank you!

2 Answers

We may use match on the 'terms' columns between the two datasets to return the same order as in the 2nd data

terms2_df_new <- terms_2_df[match(terms_1_df$terms, terms_2_df$terms),]

-output

terms_2_df_new
  terms values
4   Cat     30
5   Hat     55
1   Dog     60
6   Bat     93
3   Mat     46
2   Cow      1

You may use factor and order -

terms_2_df[order(factor(terms_2_df$terms, unique(terms_1_df$terms))), ]

#  terms values
#4   Cat     89
#5   Hat     34
#1   Dog     27
#6   Bat     93
#3   Mat     38
#2   Cow     96
Related