Latin Square

When Simply Statistics asked for a logo that encapuslated, data, simplicity and the real world I immediately thought of the Latin Square. It's all that plus an arresting historic and still relevant statistical icon. I'd also just been reading about David Cameron our PM unable on something called 'The Letterman Show' to translate 'Magna Carta' into English, surely the biggest Latin fail since Buffy thought 'Carpe Diem' was 'Fish of the Day'. I think that triggered the idea - and as I'd been looking at tilemaps earlier in the day I decide to write a latin square generator.

Then I realised I had no idea how to do that. I googled a bit and found a c++ algorithm that didn't seem to work when transmogrified into R. So I wrote my own code. I thought it would take a few minutes but it took a bit longer…err. quite a bit longer. I did waste a lot of time trying to write it in one line functional style haiku coding but it was so inscrutable that I went back to loopy loops.

# A Latin Square algorithm plotted
require(reshape2)
## Loading required package: reshape2
require(ggplot2)
## Loading required package: ggplot2
require(RColorBrewer)
## Loading required package: RColorBrewer
latinSq = function(n) {
    v = rep(NA, n^2)
    v[n * (1:n) - (n - 1)] = 1:n
    mem = 1
    for (i in 1:(n^2)) {

        if (!is.na(v[i])) 
            mem = ifelse(v[i] < n, v[i] + 1, 1)

        if (is.na(v[i])) {
            v[i] = mem
            mem = ifelse(mem < n, mem + 1, 1)
        }
    }
    dim(v) = c(n, n)
    lsqm = melt(v)

    if (n != 7) 
        gg <- ggplot(lsqm, aes(x = Var1, y = Var2, fill = value, label = LETTERS[value]))

    if (n == 7) {
        LATINSQ = c("L", "A", "T", "I", "N", "S", "Q")[lsqm$value]
        lsqm = data.frame(lsqm, LATINSQ)
        gg <- ggplot(lsqm, aes(x = Var1, y = Var2, fill = value, label = LATINSQ))
    }

    ggPrint <- gg + geom_tile() + geom_text() + scale_fill_gradientn(colours = brewer.pal(n, 
        "Spectral")) + theme_bw() + theme(axis.text.x = element_blank(), axis.text.y = element_blank(), 
        axis.title.x = element_blank(), axis.title.y = element_blank())
    ggPrint

}

Given any number n, the code will create an n-sided latin square labelling with A-Z. Actually since it uses R built-in LETTERS it will fail if n>26. When n==7 it makes a special square labelled with LATINSQ and that I think would make a nice logo.

latinSq(8)

plot of chunk latinSqgen


# possible logo
latinSq(7)

plot of chunk latinSqgen

I'm interested in this now as whilst pretty it's only one type of latin square and a design that avoided contiguous squares would be better. It might help the big 96 well-plate screens that I was asked about a while back.Too busy to think about it now :(