# Generate summary statistics about clusters as a data frame
summarizeClusterStats <- function(feature.set,        # the set of features to look at
                                   clusters,           # result of kmeans() (<clusters>$cluster)
                                   cl.num) {           # number of clusters
  
                                                                              # set up the data frame
  m <- matrix(nrow = ncol(feature.set) + 1, ncol = cl.num)
  df <- data.frame(m)
  rownames(df)[1] <- "Frequency"                                              # the first row: cluster frequencies
  for (i in 2:nrow(df)) {                                                     # the other rows: 
    rownames(df)[i] <- paste(names(feature.set)[i-1], "(mean, sd)")           # <feature> (mean, sd)
  }
  for (i in 1:ncol(df)) {
    names(df)[i] <- paste("Cluster", i)                                       # column names: Cluster <i>
  }
  
  cluster.numbers <- sort(unique(clusters))                                   # get cluster numbers, sorted
  
  df[1, ] <- as.integer(table(clusters))                                      # insert cluster frequencies
  for (j in 1:ncol(df)) {
    for (i in 2:nrow(df)) {
      indices <- which(clusters == cluster.numbers[j])                        # observations in the j-th cluster
      v <- feature.set[indices, i - 1]
      mean.v <- mean(v)
      sd.v <- sd(v)
      df[i, j] <- paste(round(mean.v, digits = 2), ", ", 
                        round(sd.v, digits = 2), sep = "")
    }
  }
  
  df
}

# Create a dataframe to compare multiple clustering results/schemes
compareMultipleClusterings <- function(comparison) {    # comparison: a list of values generated by sapply()
  
  values <- as.numeric(comparison)
  noOfRows <- attributes(comparison)$dim[1]
  noOfCols <- attributes(comparison)$dim[2]
  rows <- attributes(comparison)$dimnames[[1]]
  cols <- attributes(comparison)$dimnames[[2]]
  
  comparison.df <- data.frame(matrix(values, nrow = noOfRows, ncol = noOfCols))
  rownames(comparison.df) <- rows
  colnames(comparison.df) <- cols
  
  comparison.df
}
