writer_typer
writer_typer

Reputation: 798

How to add a column with repeating but changing sequence?

I'm trying to add a column with repeating sequence but one that changes for each group. In the example data, the group is the id column.

data <- tibble::expand_grid(id = 1:12, condition = c("a", "b", "c"))

data
id    condition
 1       a          
 1       b          
 1       c          
 2       a          
 2       b          
 2       c          
 3       a          
 3       b          
 3       c          
... and so on

I'd like to add a column called order to repeat various combinations like 1 2 3 2 3 1 3 1 2 1 3 2 2 1 3 3 2 1 for each id.

In the end, the desired output will look like this

id    condition  order
 1       a          1
 1       b          2
 1       c          3
 2       a          2
 2       b          3
 2       c          1
 3       a          3
 3       b          1
 3       c          2
... and so on

I'm looking for a simple mutate solution or base R solution. I tried generating a list of combinations but I'm not sure how to create a variable from that.

Upvotes: 1

Views: 135

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102880

You can use perms from package pracma to generate all permutations, e.g.,

data %>%
  cbind(order = c(t(pracma::perms(1:3))))

which gives

   id condition order
1   1         a     3
2   1         b     2
3   1         c     1
4   2         a     3
5   2         b     1
6   2         c     2
7   3         a     2
8   3         b     3
9   3         c     1
10  4         a     2
11  4         b     1
12  4         c     3
13  5         a     1
14  5         b     2
15  5         c     3
16  6         a     1
17  6         b     3
18  6         c     2
19  7         a     3
20  7         b     2
21  7         c     1
22  8         a     3
23  8         b     1
24  8         c     2
25  9         a     2
26  9         b     3
27  9         c     1
28 10         a     2
29 10         b     1
30 10         c     3
31 11         a     1
32 11         b     2
33 11         c     3
34 12         a     1
35 12         b     3
36 12         c     2

Upvotes: 3

Related Questions