1

Consider a vector:

dim <- c("a", "b", "c", "d")

I want to be able to create versions of the vector by dropping some variables and then using the updated vector for my loop.

For eg:

I want it to iterate to all possible vectors that can results from this:

    dim <- c("a", "b", "d")

So on and so forth. Could I do this in a loop or someway that I do not have to specify anything. Order doesn't matter, so I do not want a,b,c and c,a,b

Bruce Wayne
  • 471
  • 5
  • 18

3 Answers3

1

You can get this with:

dim <- c("a", "b", "c", "d")
> Map(combn, list(dim), 1:length(dim))

[[1]]  # All combinations of size 1
     [,1] [,2] [,3] [,4]
[1,] "a"  "b"  "c"  "d" 

[[2]]  # All combinations of size 2
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "a"  "a"  "a"  "b"  "b"  "c" 
[2,] "b"  "c"  "d"  "c"  "d"  "d" 

[[3]]  # All combinations of size 3
     [,1] [,2] [,3] [,4]
[1,] "a"  "a"  "a"  "b" 
[2,] "b"  "b"  "c"  "c" 
[3,] "c"  "d"  "d"  "d" 

[[4]]  # All combinations of size 4
     [,1]
[1,] "a" 
[2,] "b" 
[3,] "c" 
[4,] "d" 
NM_
  • 1,887
  • 3
  • 12
  • 27
0

if you are looking for all combinations of dim you can check out the function combn from the combinat package:

combinat::combn(letters[1:4], 1, simplify = F)

    [[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

[[4]]
[1] "d"

combinat::combn(letters[1:4], 2, simplify = F)
combinat::combn(letters[1:4], 3, simplify = F)
combinat::combn(letters[1:4], 4, simplify = F)
Cettt
  • 11,460
  • 7
  • 35
  • 58
  • I do not care about the order, I do not want repetition of the same 4 elements. I want like ```[[1]] [1] "a" "b" [[2]][1]"a" "b" "c" ..... ``` – Bruce Wayne Apr 03 '19 at 20:17
  • Ok i see, you are looking for combinations then :). I edited my answer – Cettt Apr 03 '19 at 20:25
0

In base R I would use either of the for-loop, sapply or lapply

for-loop

for (i in seq_along(dim)) {
  print(dim[-i])
}

[1] "b" "c" "d"
[1] "a" "c" "d"
[1] "a" "b" "d"
[1] "a" "b" "c"

sapply

t( sapply(seq_along(dim), function(i) dim[-i]) )

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

lapply

lapply(seq_along(dim), function(i) dim[-i])

[[1]]
[1] "b" "c" "d"

[[2]]
[1] "a" "c" "d"

[[3]]
[1] "a" "b" "d"

[[4]]
[1] "a" "b" "c"
cropgen
  • 1,920
  • 15
  • 24