0

I would like to find k-element variations of n elements with repetition not allowed as defined in this document. I found several posts considering combinations and permutations but non dealing with variations. From the cited document, "variations are arrangements of selections of objects, where the order of the selected objects matters." I cannot find suitable function in the combinat package. I want to achieve result equivalent to this answer but for variations, not combinations.

An example: We have n=4 elements and want to find the k=2 element variations. There should be 12 possible variations:

1 and 2; 1 and 3; 1 and 4;

2 and 1; 2 and 3; 2 and 4;

3 and 1; 3 and 2; 3 and 4;

4 and 1; 4 and 2; 4 and 3.

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
ABC
  • 336
  • 1
  • 2
  • 9
  • 2
    Unless I’m overlooking something this is equivalent to the combinations of n, take m elements both forward and backwards. For your example: `cbind(combn(1 : 4, 2L), combn(4 : 1, 2L))`. – Konrad Rudolph Apr 21 '23 at 07:56

1 Answers1

3

Problably you can use expand.grid and then filter out the rows with duplicates

n <- 4
k <- 2
d <- expand.grid(rep(list(seq(n)), k))
d[apply(d, 1, anyDuplicated) == 0, ]

which gives

   Var1 Var2
2     2    1
3     3    1
4     4    1
5     1    2
7     3    2
8     4    2
9     1    3
10    2    3
12    4    3
13    1    4
14    2    4
15    3    4

If you want more programming exercises, you can try coding with your own function

n <- 4
k <- 2

f <- function(n, k) {
  if (k == 1) {
    return(1:n)
  }
  r <- c()
  for (l in Recall(n, k - 1)) {
    v <- 1:n
    u <- v[!v %in% l]
    r <- c(r, Map(c, list(l), u))
  }
  r
}

which gives

> f(n, k)
[[1]]
[1] 1 2

[[2]]
[1] 1 3

[[3]]
[1] 1 4

[[4]]
[1] 2 1

[[5]]
[1] 2 3

[[6]]
[1] 2 4

[[7]]
[1] 3 1

[[8]]
[1] 3 2

[[9]]
[1] 3 4

[[10]]
[1] 4 1

[[11]]
[1] 4 2

[[12]]
[1] 4 3
Joseph Wood
  • 7,077
  • 2
  • 30
  • 65
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81