0

What R command generates all possible ordered combinations of length k?

For example from this vector:

a,b,c,d  

It want to generate all combinations of length 3 but only those ones where the order is conserved:

a,b,c  
a,b,d  
a,c,d  
b,c,d 

Or If I have this vector

a,b,7,d,e

I want to do the same for length 2:

a,b  
a,7  
a,d  
a,e  
b,7  
b,d  
b,e  
7,d  
7,e  
d,e

combn doesn't work here because it gives you all possible combinations including reversed ones such as
c,b
In simple cases I could try to do it with expand.grid but both methods would need further processing.
Maybe there is a base function (or package) able to do what I want or even accepting more complex conditions.

PD: When I say "ordered" I'm speaking about the order of appearance in the starting vector. I don't mean the typographic order, though in my example they are the same.

989
  • 12,579
  • 5
  • 31
  • 53
skan
  • 7,423
  • 14
  • 59
  • 96
  • 2
    If I do `combn(x, 3, FUN = toString)` It gives the expected output - where `x <- letters[1:4]` – Sotos Jun 08 '17 at 11:25
  • Also, this https://stackoverflow.com/questions/21984830/creating-new-ids-two-way-from-two-vectors could be of interest for your question. – nadizan Jun 08 '17 at 11:37

1 Answers1

1

You can use combn in base R:

vec <- c("a", "b", "c", "d")
len <- 2
combn(length(vec), len, function(x) vec[x])

#    [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] "a"  "a"  "a"  "b"  "b"  "c" 
#[2,] "b"  "c"  "d"  "c"  "d"  "d" 

Of length 3:

combn(length(vec), 3, function(x) vec[x])

#     [,1] [,2] [,3] [,4]
#[1,] "a"  "a"  "a"  "b" 
#[2,] "b"  "b"  "c"  "c" 
#[3,] "c"  "d"  "d"  "d" 

OR as @Sotos pointed out in the comments:

combn(vec, len)
989
  • 12,579
  • 5
  • 31
  • 53