Generating Random Lattice Structures with Efficient Vertex Distribution in R

Here is the complete code in a single function:

library(data.table)

f <- function(g, n) {
  m <- length(g)
  dt <- setDT(as.data.frame(g))
  dt[, group := 0]
  used <- logical(m)
  s <- sample(1:m, n)
  used[s] <- TRUE
  m <- m - n
  dt[from %in% s, group := .GRP, from]

  while (m > 0) {
    dt2 <- unique(dt[group != 0 & !used[to], .(grow = to, onto = group)][sample(.N)])
    dt[dt2, on = .(from = grow), group := onto]
    used[dt2$to] <- TRUE
    m <- m - nrow(dt2)
  }

  unique(dt[, to := NULL])[, .(vertices = from, N)]
}

g <- make_lattice(c(100, 100))
set.seed(907044864)
f(g, 10)

Note that I’ve also added system.time(dt <- f(make_lattice(c(100, 100)), 10)) to test the performance of the function.


Last modified on 2023-06-01