[R] A "matching problem"

Petr Savicky savicky at cs.cas.cz
Mon Jul 30 20:04:45 CEST 2012


On Mon, Jul 30, 2012 at 08:40:59PM +0545, Christofer Bogaso wrote:
> Dear all, I was encountering with a typical Matching problem and was 
> wondering whether R can help me to solve it directly.
> 
> Let say, I have 2 vectors of equal length:
> vector1 <- LETTERS[1:6]
> vector2 <- letters[1:6]
> 
> Now I need to match these 2 vectors with all possible ways like:
> 
> (A,B,C,D,E) & (a,b,c,d,e) is 1 match. Another match can be (A,B,C,D,E) & 
> (b,a,c,d,e), however there cant be any duplication.

Hi.

If i understand correctly, all matches are obtained by taking all
permutations of (a,b,c,d,e) and relating them to unchanged (A,B,C,D,E).
Try the following.

  library(permute)
  vector2 <- letters[1:3]
  p <- allPerms(length(vector2), observed=TRUE)
  matrix(vector2[p], nrow=nrow(p), ncol=ncol(p))
  
       [,1] [,2] [,3]
  [1,] "a"  "b"  "c" 
  [2,] "a"  "c"  "b" 
  [3,] "b"  "a"  "c" 
  [4,] "b"  "c"  "a" 
  [5,] "c"  "a"  "b" 
  [6,] "c"  "b"  "a" 

The rows of the resulting matrix are all permutations of vector2.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list