Joe
Joe

Reputation: 1768

How to order a data frame with duplicates by a vector?

I have a data frame with two columns (both containing duplicates) that I want to order by a vector. Here is a MWE:

target_order <- c("a", "b", "c")
df <- data.frame(col1 = c("c", "a", "b", "a", "a", "c", "c", "b"),
                 col2 = c(1, 1, 2, 5, 4, 2, 6, 7))

My goal is to order df by target_order based on col1. Following Order data frame rows according to vector with specific order I tried df[match(target_order, df$col1), ], but this only led to:

> df[match(ind_order, df$col1), ]
  col1 col2
2    a    1
3    b    2
1    c    1

Who can help? (A solution in base R would be cool.)

Upvotes: 0

Views: 1394

Answers (1)

Pierre L
Pierre L

Reputation: 28441

Your final desired output was not given, but maybe something like this

df[order(match(df$col1, target_order)),]
  col1 col2
2    a    1
4    a    5
5    a    4
3    b    2
8    b    7
1    c    1
6    c    2
7    c    6

Upvotes: 3

Related Questions