rxk011 rxk011 - 1 month ago 5
R Question

How do I generate all the vectors by swapping two positions?

Suppose I have a column vector of [1 1 1 2 2 2 3 3 3] and I want to generate all the different column vectors only by switching two positions. For an example, one such vector would be
[1 1 3 2 2 2 1 3 3].

Answer

Try this (it gives you a data frame each row of which is a unique vector with 2 elements swapped from the original vector, there are 28 such unique vectors, including the original one):

v <- c(1,1,1,2,2,2,3,3,3)
unique(t(apply(t(combn(1:length(v), 2)), 1, function(x) {v[x] <- v[rev(x)]; v})))

with output:

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
 [1,]    1    1    1    2    2    2    3    3    3 # original one
 [2,]    2    1    1    1    2    2    3    3    3 # swap 1st & 4th elements
 [3,]    2    1    1    2    1    2    3    3    3 # swap 1st & 5th
 [4,]    2    1    1    2    2    1    3    3    3 # ...
 [5,]    3    1    1    2    2    2    1    3    3
 [6,]    3    1    1    2    2    2    3    1    3
 [7,]    3    1    1    2    2    2    3    3    1
 [8,]    1    2    1    1    2    2    3    3    3
 [9,]    1    2    1    2    1    2    3    3    3
[10,]    1    2    1    2    2    1    3    3    3
[11,]    1    3    1    2    2    2    1    3    3
[12,]    1    3    1    2    2    2    3    1    3
[13,]    1    3    1    2    2    2    3    3    1
[14,]    1    1    2    1    2    2    3    3    3
[15,]    1    1    2    2    1    2    3    3    3
[16,]    1    1    2    2    2    1    3    3    3
[17,]    1    1    3    2    2    2    1    3    3
[18,]    1    1    3    2    2    2    3    1    3
[19,]    1    1    3    2    2    2    3    3    1
[20,]    1    1    1    3    2    2    2    3    3
[21,]    1    1    1    3    2    2    3    2    3
[22,]    1    1    1    3    2    2    3    3    2
[23,]    1    1    1    2    3    2    2    3    3
[24,]    1    1    1    2    3    2    3    2    3
[25,]    1    1    1    2    3    2    3    3    2
[26,]    1    1    1    2    2    3    2    3    3
[27,]    1    1    1    2    2    3    3    2    3
[28,]    1    1    1    2    2    3    3    3    2  # swap 6th & 9th
Comments