37
|
1 # load sparse matrix package
|
|
2 suppressPackageStartupMessages(library('Matrix'))
|
|
3
|
|
4 # access a numeric column
|
|
5 get_numeric <- function(table, column_key) {
|
|
6 column <- as.numeric(column_key)
|
53
|
7 column_data <- suppressWarnings(as.numeric(as.character(table[column][[1]])))
|
37
|
8 return (c(column_data))
|
|
9 }
|
|
10
|
|
11 # access a label column
|
|
12 get_label <- function(table, column_key) {
|
|
13 column <- as.numeric(column_key)
|
|
14 return (c(table[column]))
|
|
15 }
|
|
16
|
|
17 # inflate three columns into matrix
|
|
18 matrify <- function (data) {
|
|
19 if (ncol(data) != 3)
|
|
20 stop('Data frame must have three column format')
|
|
21 plt <- data[, 1]
|
|
22 spc <- data[, 2]
|
|
23 abu <- data[, 3]
|
|
24 plt.codes <- levels(factor(plt))
|
|
25 spc.codes <- levels(factor(spc))
|
|
26 taxa <- Matrix(0, nrow=length(plt.codes), ncol=length(spc.codes), sparse=TRUE)
|
|
27 row <- match(plt, plt.codes)
|
|
28 col <- match(spc, spc.codes)
|
|
29 for (i in 1:length(abu)) {
|
|
30 taxa[row[i], col[i]] <- abu[i]
|
|
31 }
|
|
32 colnames(taxa) <- spc.codes
|
|
33 rownames(taxa) <- plt.codes
|
|
34 taxa
|
|
35 }
|
|
36
|
|
37 # flatten data.frame into three column format
|
|
38 flatten <- function(my_matrix) {
|
|
39 summ <-summary(my_matrix)
|
|
40 summ <- data.frame(i=rownames(my_matrix)[summ$i], j=colnames(my_matrix)[summ$j], x=summ$x)
|
|
41 summ
|
|
42 }
|
|
43
|
|
44 # wrapper
|
|
45 wrapper <- function(table, columns, options) {
|
|
46
|
|
47 # initialize output list
|
|
48 l <- list()
|
|
49
|
|
50 # get number of columns
|
|
51 n = length(columns)
|
|
52
|
|
53 # consistency check
|
|
54 if (n %% 3 != 0) {
|
|
55 print ('heatmap::wrapper() - Data not consistent (n mod 3 != 0)')
|
|
56 return (l)
|
|
57 }
|
|
58
|
|
59 # create index sequence
|
|
60 index = seq(1, n, by=3)
|
|
61
|
|
62 # get keys
|
|
63 keys = names(columns)
|
|
64
|
|
65 # loop through blocks
|
|
66 for (i in index) {
|
|
67 # create columns
|
|
68 ci <- get_label(table, columns[keys[i]])
|
|
69 cj <- get_label(table, columns[keys[i+1]])
|
|
70 cx <- get_numeric(table, columns[keys[i+2]])
|
|
71
|
|
72 # create a frame from columns
|
|
73 my_frame <- data.frame(ci=ci, cj=cj, cx=cx)
|
|
74
|
|
75 # create matrix out of the frame
|
|
76 my_matrix <- matrify(my_frame)
|
|
77
|
|
78 # create/cluster matrix
|
|
79 row_order <- hclust(dist(my_matrix))$order
|
|
80 col_order <- hclust(dist(t(my_matrix)))$order
|
|
81
|
|
82 # reorder matrix
|
|
83 my_matrix <- my_matrix[row_order, col_order]
|
|
84
|
|
85 # transform back to three columns
|
53
|
86 my_flatmatrix = flatten(my_matrix)
|
37
|
87
|
|
88 # append to result list
|
|
89 l <- append(l, list(my_flatmatrix$i))
|
|
90 l <- append(l, list(my_flatmatrix$j))
|
|
91 l <- append(l, list(my_flatmatrix$x))
|
|
92 }
|
|
93
|
|
94 # return
|
|
95 return (l)
|
|
96 }
|