# Monte Carlo testing of classification groups

**Last Resort Software**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This is another article on the theme of defining groups in a hierarchical classification. A previous article described homogeneity analysis to visualize how any well any number of groups, defined at the same level accounts for the variability in the dataset, as measured by within-group pairwise distances. Here we will look at testing whether splitting a particular group into two daughter groups is supported by the data.

Suppose we have a group G containing N objects which we are considering splitting into two groups G1 and G2 consisting of N1 and N2 objects respectively. A Monte Carlo approach to testing whether this is worth doing is as follows:

1. Calculate the mean within-group pairwise distance that would result from defining G1 and G2.

2. Randomly allocate objects to two groups of sizes N1 and N2 and calculate the resulting mean within-group pairwise distance.

3. Repeat step 2 a large number of times (e.g. 999) to create a vector of Monte Carlo means. Add the actual mean from step 1 to this vector.

4. Calculate an empirical probability from the position of the actual mean in the sorted vector from step 3.

If the groups G1 and G2 are meaningful, the probability from step 4 should be low, ie. the actual mean should be lower than most or all of the Monte Carlo means.

Below is the R code for this algorithm. It takes as input a distance matrix; a vector of group IDs for all objects; the IDs of the two groups being tested and the number of Monte Carlo means to sample.

<br /><br />testGroups <- function (d, grp, g1=1, g2=2, nsamples=999)<br />{<br /># Performs a Monte-Carlo test of the informativeness of two groups of<br /># objects by comparing the actual mean of within-group pairwise distances<br /># to a vector of means derived by randomly allocating objects to the<br /># two groups. If the two groups are informative, the actual mean should<br /># be less than most or all of the Monte-Carlo means.<br />#<br /># Arguments:<br /># d - distance matrix<br /># grp - vector of group ids for all objects in the distance matrix<br /># (ids of objects outside the two groups being considered can<br /># be set to arbitrary values)<br /># g1 - id of first group to be tested<br /># g2 - id of second group to be tested<br /># nsamples - number of random groupings to generate (if possible)<br />#<br /># The function attempts to generate unique allocations using the following rules:<br />#<br /># 1. If nsamples is greater than choose(N1+N2, N1) it is reduced accordingly <br /># and a warning message issued. All unique allocations are then <br /># generated systematically.<br />#<br /># 2. If nsamples is greater than choose(N1+N2, N1) / 20 allocations are generated<br /># systematically to guarantee uniqueness. <br />#<br /># 3. If nsamples is less than choose(N1+N2, N1) / 20, allocations are<br /># generated randomly with no check for uniqueness to reduce running<br /># time.<br />#<br /># The function invisibly returns a list with the following elements:<br /># actual.mean - the mean within-group pairwise distance for actual groupings<br /># prob - probability of observing a mean less than or equal to the actual<br /># mean calculated by comparing the actual value to a vector of <br /># means from random allocations plus the actual mean<br /># mc.mean - mean within-group pairwise distance for each random allocation<br />#<br /># Michael Bedward, August 2010<br /><br /> # Constants<br /> SYSTEMATIC <- 1<br /> RANDOM <- 2<br /><br /> Nobj <- length(grp)<br /> if (length(d) != Nobj*(Nobj-1)/2) {<br /> stop("Number of objects differs between dist object and group vector")<br /> }<br /> <br /> N1 <- sum(grp == g1)<br /> N2 <- sum(grp == g2)<br /> if (N1 == 1 & N2 == 1) {<br /> stop("Can't test split between two singleton groups")<br /> }<br /><br /> objects <- which(grp == g1 | grp == g2)<br /> <br /> Nc <- choose(N1+N2, N1)<br /> <br /> if (nsamples >= Nc/20) {<br /> if (nsamples > Nc) {<br /> warning(paste("Requested number of samples (", nsamples, ") exceeds possible rearrangements (", Nc, ")", sep=""))<br /> nsamples <- Nc<br /> }<br /> sample.method <- SYSTEMATIC<br /> } else {<br /> sample.method <- RANDOM<br /> }<br /><br /> # Helper function: calculates total pairwise distance between<br /> # objects within a group. Returns total and number of <br /> # pairwise distances<br /> calc.grp.dist <- function(grp.obj) {<br /> if (length(grp.obj) == 1) {<br /> return( c(0, 0) )<br /> }<br /><br /> pairwise <- combn(sort(grp.obj), 2)<br /> di <- Nobj * (pairwise[1,] - 1) - pairwise[1,]*(pairwise[1,]-1)/2 + pairwise[2,]-pairwise[1,]<br /> c(sum(d[di]), length(di)) <br /> }<br /><br /> # Helper function: calculates mean within-group distance.<br /> # Arg indices holds the indices of elements in the objects vector for<br /> # one of the groups.<br /> calc.mean <- function(indices) {<br /> g1dist <- calc.grp.dist(objects[indices])<br /> g2dist <- calc.grp.dist(objects[-indices])<br /> (g1dist[1] + g2dist[1]) / (g1dist[2] + g2dist[2])<br /> }<br /><br /> samples <- numeric(nsamples+1)<br /><br /> # actual within-group mean distance<br /> samples[1] <- calc.mean(which(grp == g1))<br /><br /> # randomly allocate objects to groups and calculate means<br /> Nmin <- min(N1, N2)<br /> k <- 2<br /> if (sample.method == SYSTEMATIC) {<br /> combns <- combn(N1+N2, Nmin)[, sample(Nc, nsamples)]<br /> } else { # sample.method == RANDOM<br /> combns <- replicate(nsamples, sample(N1+N2, Nmin))<br /> }<br /><br /> apply( combns, 2, function(x){samples[k] <<- calc.mean(x); k <<- k+1} )<br /> prob <- ecdf(samples)(samples[1])<br /> print(paste("Prob =", prob, "from", nsamples, "samples plus actual value"))<br /> invisible(list(actual.mean=samples[1], prob=prob, mc.means=samples[-1]))<br />}<br />

**leave a comment**for the author, please follow the link and comment on their blog:

**Last Resort Software**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.