# Permutation Pyramid

So I had to make a combination of different values based on elements in a vector. With a few tweaks and what not I made a little function to find all the combinations and permutations of a given vector. Enjoy

The function:

```# creat a list of combinations and
# permutations of elements from
# a single vector. This requires
# a few libraries:
# library( dplyr )
# library( purrr )
# library( combinat )

# "order.matters" is means that
# for every combination of elements
# find every order they can be
# arranged.

permutation.pyramid <- function( v, order.matters = TRUE ){

# get the unique combinations of elements
# and flatten them into a one dimensional list
out <- 1:length(v) %>%
lapply(function( x ){
combn( v, x ) %>% as.data.frame()
}) %>%
purrr::flatten() %>%
unname()

# if order.matters then find all the
# arrangements of each combination
if( order.matters ){
out <- out %>%
lapply(function( x ){
combinat::permn( x )
}) %>%
purrr::flatten()
}

# return list of permutations
return( out )
}

```

Use and examples.

Find all combinations and permutations of a given vector

```> test <- c("A","B","C")
> permutation.pyramid( test )
[[1]]
[1] "A"

[[2]]
[1] "B"

[[3]]
[1] "C"

[[4]]
[1] "A" "B"

[[5]]
[1] "B" "A"

[[6]]
[1] "A" "C"

[[7]]
[1] "C" "A"

[[8]]
[1] "B" "C"

[[9]]
[1] "C" "B"

[[10]]
[1] "A" "B" "C"

[[11]]
[1] "A" "C" "B"

[[12]]
[1] "C" "A" "B"

[[13]]
[1] "C" "B" "A"

[[14]]
[1] "B" "C" "A"

[[15]]
[1] "B" "A" "C"
```

Find all combinations of vector

```> test <- c("A","B","C")
> permutation.pyramid( test, order.matters = FALSE )
[[1]]
[1] "A"

[[2]]
[1] "B"

[[3]]
[1] "C"

[[4]]
[1] "A" "B"

[[5]]
[1] "A" "C"

[[6]]
[1] "B" "C"

[[7]]
[1] "A" "B" "C"
```

Anyways I hope that’ll be useful for someone!