Tom
Tom

Reputation: 2341

Putting rows in a specific order, keeping another row in the same relative order

I have data as follows:

dat <- data.frame(type=c("Y","Y","Y","Y","X","X","X","X","Z","Z","Z","Z"), cat=c("A", "B", "C", "D","A", "B", "C", "D","A", "B", "C", "D"), id=c(1,2,3,4,5,6,7,8,9,10,11,12))

   type cat id
1     Y   A  1
2     Y   B  2
3     Y   C  3
4     Y   D  4
5     X   A  5
6     X   B  6
7     X   C  7
8     X   D  8
9     Z   A  9
10    Z   B 10
11    Z   C 11
12    Z   D 12

I need the rows to be sorted by type in the order x <- c("Z", "X", "Y"), while keeping the order of cat in tact.

Because the rows are double the following does not work.

library(dplyr)

x <- c("Z", "X", "Y")
dat %>%
  slice(match(x, type))

I tried to adapt x:

strat_order_multiple_cat  <- as.vector()
for (i in seq_along(x)){
   temp <- rep(x[[i]], length( unique(dat$cat) ) )
   strat_order_multiple_cat <- append(strat_order_multiple_cat,temp)
}

dat %>%
  slice(match(strat_order_multiple_cat , type))

But that gives:

   type cat
1     Z   A
2     Z   A
3     Z   A
4     Z   A
5     X   A
6     X   A
7     X   A
8     X   A
9     Y   A
10    Y   A
11    Y   A
12    Y   A

How should I do this?

Upvotes: 1

Views: 47

Answers (1)

Quinten
Quinten

Reputation: 41225

You can create a factor based on the x targets and slice and order it like this:

library(dplyr)
x <- c("Z", "X", "Y")
dat %>%
  slice(order(factor(type, x)))

Output:

   type cat
1     Z   A
2     Z   B
3     Z   C
4     Z   D
5     X   A
6     X   B
7     X   C
8     X   D
9     Y   A
10    Y   B
11    Y   C
12    Y   D

Upvotes: 1

Related Questions