3 min read

Generating Combinations of Levels

I have a linear model with a 4-level factor in it. I wanted to generate all possible level combinations of this factor. I couldn’t find a function to help me do this in R, so I created my own.

combLevel <- function(n) {
  B <- matrix(1)
  for(i in 2:n) {
    maxB <- apply(B, 1, max) + 1
    B <- B[rep(1:nrow(B), maxB), ]
    B <- cbind(B, unlist(lapply(maxB, seq, 1, -1)))
  }
  dimnames(B) <- list(NULL, NULL)
  B
}

With 4 levels, this led to a total of 15 combinations, 1 with 4 levels, 6 with 3 levels, 7 with 2 levels, and 1 with 1 level.

combLevel(4)
##       [,1] [,2] [,3] [,4]
##  [1,]    1    2    3    4
##  [2,]    1    2    3    3
##  [3,]    1    2    3    2
##  [4,]    1    2    3    1
##  [5,]    1    2    2    3
##  [6,]    1    2    2    2
##  [7,]    1    2    2    1
##  [8,]    1    2    1    3
##  [9,]    1    2    1    2
## [10,]    1    2    1    1
## [11,]    1    1    2    3
## [12,]    1    1    2    2
## [13,]    1    1    2    1
## [14,]    1    1    1    2
## [15,]    1    1    1    1

How did I come up with the function? I pictured the problem as a bifurcating tree, assigning each of the original levels to a new level, one at a time. At each step in the tree, the next level would either be different from one of the previous levels, or the same as one of the previous levels.

library(DiagrammeR)
library(tidyverse)

nodes <- create_node_df(
  n = 23,
  nodes = 1:23,
  type = "number",
  label = c(1,  2:1,  3:1, 2:1,  4:1, 3:1, 3:1, 3:1, 2:1))

edges <- create_edge_df(
  from = rep(1:8, c(2, 3, 2, 4, 3, 3, 3, 2)),
  to =   2:23,
  rel = "related")

g <- create_graph(nodes_df=nodes, edges_df=edges) %>%
  set_global_graph_attrs(attr="layout", value="dot", attr_type="graph")

render_graph(g)