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)
%3 1 1 2 2 1->2 3 1 1->3 4 3 2->4 5 2 2->5 6 1 2->6 7 2 3->7 8 1 3->8 9 4 4->9 10 3 4->10 11 2 4->11 12 1 4->12 13 3 5->13 14 2 5->14 15 1 5->15 16 3 6->16 17 2 6->17 18 1 6->18 19 3 7->19 20 2 7->20 21 1 7->21 22 2 8->22 23 1 8->23