0

I'm trying to get all the combinations of a vector. I have

x <- c(1,2,3)

I need to get all the possible combinations without specifying the number of elements needed and without taking into account the order (the solution {2,3,1} is the same as {1,2,3}). For example, the result would be:

{}
{3}
{2}
{2,3}
{1}
{1,3}
{1,2}
{1,2,3}

An approximation would be to make the following table:

Tabla lógica

I am sure that there must be some function that performs this task instead of creating the table and forming the solutions from it, since it is not very tedious.

Dragg
  • 83
  • 2
  • 11
  • You are looking for the Power set. Check out the `powerset` function from the library `rje`. – Joseph Wood Feb 18 '19 at 13:49
  • @JosephWood oh yes, this was I looking for, you can put this comment like an answer for check it? – Dragg Feb 18 '19 at 14:54
  • I am not able to post as this question has been marked as a duplicate. Either way, I'm glad you were able to figure it out. – Joseph Wood Feb 18 '19 at 15:26

1 Answers1

2

Use expand.grid

out <- expand.grid(rep(list(c(1, 0)), length(x)))
out
#  Var1 Var2 Var3
#1    1    1    1
#2    0    1    1
#3    1    0    1
#4    0    0    1
#5    1    1    0
#6    0    1    0
#7    1    0    0
#8    0    0    0

If we need the combinations - as a list - we might do

split(out * col(out), 1:nrow(out))
#$`1`
#[1] 1 2 3
#
#$`2`
#[1] 0 2 3
#
#$`3`
#[1] 1 0 3
#
#$`4`
#[1] 0 0 3
#
#$`5`
#[1] 1 2 0
#
#$`6`
#[1] 0 2 0
#
#$`7`
#[1] 1 0 0
#
#$`8`
#[1] 0 0 0

Or if we don't need the 0s we might do

by(out * col(out), 1:nrow(out), FUN = function(x) x[x != 0])

(by is short for lapply(split(... )

markus
  • 25,843
  • 5
  • 39
  • 58
  • I may not have explained myself well, I do not need to create the table, I need to create the combinations, the use of the table has been an example in which I approach the solution – Dragg Feb 18 '19 at 12:33
  • @Draggluon Updated my answer. Hope this helps. – markus Feb 18 '19 at 12:41