4

I'm trying to write a program in R that when, given a vector, will return all possible tuples of elements from that vector.

For example: tuples(c('a','b','c')) = c('a','b','c'); c('a','b'); c('a','c'), c('b','c'); c('a'); c('b'); c('c')

I think it should return a list of vectors.

For reference, here is a program that does a similar function in Stata.

Metrics
  • 15,172
  • 7
  • 54
  • 83
Zach
  • 29,791
  • 35
  • 142
  • 201

1 Answers1

5

You can use combn:

x <- 1:3
unlist(lapply(x, function(n) combn(x, n, simplify=FALSE)), recursive=FALSE)
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
  • @Zach, in the general case where x can be of any class, you can treat this as working on the indices of x, and then use the result to index x. X_orig <- c('a','b','c'); x <- seq_along(X_orig); xi <- (above); lapply(xi, function(i) X_orig[i]) – Hong Ooi Mar 09 '11 at 02:53
  • 1
    no need for that. `x <- letters[1:3]` and then you do the lapply over `1:length(x)`. Works just as fine. – Joris Meys Mar 09 '11 at 14:24
  • This answer doesn't generate what it is desired . It generate more tuples than it should ! – Julien Aug 07 '22 at 11:32