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!

Confidence Intervals

A small little function written in R to get the 95% confidence intervals and some quick stats of a vector. I found this useful in error reporting in some stats. I got the concept from this tutorial.

This does require the dplyr library

Function

library( dplyr )

ci <- function( x ){
  cnf <- dplyr::tibble(
    mean = mean( x, na.rm = TRUE),
    st.dev = sd( x, na.rm = TRUE),
    n = length( x ),
    error = qnorm( 0.975 ) * st.dev / sqrt( n ),
    ci05 = mean - error,
    ci95 = mean + error
  )
  
  cat( cnf$mean, "(", cnf$ci05, "-", cnf$ci95, ")\n" )
  return( cnf )
}

Use

> x <- sample(10)
> ci(x)
5.5 ( 3.623477 - 7.376523 )
# A tibble: 1 x 6
   mean st.dev     n error  ci05  ci95
  <dbl>  <dbl> <int> <dbl> <dbl> <dbl>
1   5.5   3.03    10  1.88  3.62  7.38