0

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.)

Joe
  • 1,628
  • 3
  • 25
  • 39

1 Answers1

3

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
Pierre L
  • 28,203
  • 6
  • 47
  • 69