-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASCA_module.R
More file actions
1443 lines (1315 loc) · 57 KB
/
ASCA_module.R
File metadata and controls
1443 lines (1315 loc) · 57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ASCA Model
buildModelUI <- function(id) {
ns <- NS(id)
tagList(
tabItem("buildmodel",
fluidRow(
box(width = 3, status = "primary",
textInput(ns("include.factors"), "Include factors", "")
),
box(width = 3, status = "primary",
textInput(ns("include.interactions"), "Include interactions", "")
),
box(width = 3, status = "primary",
textInput(ns("include.combinations"), "Combine terms", "")
)
),
fluidRow(
box(width = 9, status = "primary", title = "Model",
tableOutput(ns("model"))
)
),
fluidRow(
box(width = 9, status = "primary", title = "Variances",
tableOutput(ns("variances"))
)
)
)
)
}
makeFactorsUI <- function(id) {
ns <- NS(id)
fluidPage(
fluidRow(
box(status = "primary", width = 3,
selectInput(ns("choose.factor"),
"Factor",
choices = "", selected = ""),
conditionalPanel(condition = paste0("input['", ns("fpt"), "'] == 'biplot' |
input['", ns("fpt"), "'] == 'scores' "),
tags$hr(style="border-color: black;"),
checkboxInput(ns("fplotprojctns"), "Projections", TRUE)
)
),
box(status = "primary", width = 3,
radioButtons(ns('fpt'), "Plot",
c("Scores" = "scores",
"Levels" = "levels",
"Biplot" = "biplot",
"Loadings" = "loadings"),
selected = "scores")
),
box(width = 3, status = "primary",
div(style="display: inline-block;vertical-align:top; width: 100px;",
selectInput(ns("factor.pc1"),
"First PC",
choices = "",
selected = "")
),
div(style=
"display: inline-block;vertical-align:top; width: 20px; ",""),
div(style="display: inline-block;vertical-align:top; width: 100px;",
selectInput(ns("factor.pc2"),
"Second PC",
choices = "",
selected = "")
)
)
# conditionalPanel(condition = paste0("input['", ns("fpt"), "'] == 'biplot' "),
# box(width = 3, status = "primary",
# div(style="display: inline-block;vertical-align:top; width: 100px;",
# uiOutput(ns("fbiplot"))
# )
# )
# )
),
fluidRow(
box(width = 12, status = "primary",
plotOutput(ns("factors"))
)
)
)
}
makeInteractionsUI <- function(id) {
ns <- NS(id)
tagList(
fluidRow(
box(status = "primary", width = 3,
selectInput(ns("choose.interaction"),
"Interaction",
choices = "", selected = ""),
conditionalPanel(condition = paste0("input['", ns("ipt"), "'] == 'biplot' |
input['", ns("ipt"), "'] == 'scores' "),
tags$hr(style="border-color: black;"),
checkboxInput(ns("iplotprojctns"), "Projections", TRUE)
)
),
box(status = "primary", width = 3,
radioButtons(ns('ipt'),
"Plot",
c("Scores" = "scores",
"Levels" = "levels",
"Biplot" = "biplot",
"Loadings" = "loadings"),
selected = "scores")
),
box(width = 3, status = "primary",
div(style="display: inline-block;vertical-align:top; width: 100px;",
selectInput(ns("interaction.pc1"),
"First PC",
choices = "",
selected = "")
),
div(style="display: inline-block;vertical-align:top; width: 20px;",""),
div(style="display: inline-block;vertical-align:top; width: 100px;",
selectInput(ns("interaction.pc2"),
"Second PC",
choices = "",
selected = "")
)
),
conditionalPanel(condition = paste0("input['", ns('ipt'), "'] == 'levels' "),
box(width = 3,
selectInput(ns("ixvalues"),
"Factor on x-axis",
choices = "",
selected = ""),
selectInput(ns("igroupfactor"),
"Color by factor",
choices = "",
selected = "")
)
),
conditionalPanel(condition = paste0("input['", ns('ipt'), "'] == 'scores' |
input['", ns('ipt'), "'] == 'biplot'"),
box(width = 3,
selectInput(ns("icolor"),
"Color",
choices = "",
selected = ""),
selectInput(ns("ishape"),
"Shape",
choices = "",
selected = "")
)
)
# conditionalPanel(condition = paste0("input['", ns("ipt"), "'] == 'biplot' "),
# box(width = 3, status = "primary",
# div(style="display: inline-block;vertical-align:top; width: 100px;",
# uiOutput(ns("ibiplot"))
# )
# )
# )
),
fluidRow(
box(width = 12, status = "primary",
plotOutput(ns("interactions"))
)
)
)
}
makeCombinationsUI <- function(id) {
ns <- NS(id)
tagList(
fluidRow(
box(status = "primary", width = 3,
selectInput(ns("choose.combination"),
"Combination",
choices = "", selected = ""),
conditionalPanel(condition = paste0("input['", ns("cpt"), "'] == 'biplot' |
input['", ns("cpt"), "'] == 'scores' "),
tags$hr(style="border-color: black;"),
checkboxInput(ns("cplotprojctns"), "Projections", TRUE)
)
),
box(status = "primary", width = 3,
radioButtons(ns('cpt'), "Plot",
c("Scores" = "scores",
"Levels" = "levels",
"Biplot" = "biplot",
"Loadings" = "loadings"),
selected = "scores")
),
box(width = 3, status = "primary",
div(style="display: inline-block;vertical-align:top; width: 100px;",
selectInput(ns("combination.pc1"),
"First PC",
choices = "",
selected = "")
),
div(style=
"display: inline-block;vertical-align:top; width: 20px;", ""),
div(style=
"display: inline-block;vertical-align:top; width: 100px;",
selectInput(ns("combination.pc2"),
"Second PC",
choices = "",
selected = "")
)
),
conditionalPanel(paste0("input['", ns("cpt"), "'] == 'levels' "),
box(width = 3,
selectInput(ns("cxvalues"),
"Factor on x-axis",
choices = "",
selected = ""),
selectInput(ns("cgroupfactor"),
"Color by factor",
choices = "",
selected = "")
)
),
conditionalPanel(condition = paste0("input['", ns('cpt'), "'] == 'scores' |
input['", ns('cpt'), "'] == 'biplot'"),
box(width = 3,
selectInput(ns("ccolor"),
"Color",
choices = "",
selected = ""),
selectInput(ns("cshape"),
"Shape",
choices = "",
selected = "")
)
)
# conditionalPanel(condition = paste0("input['", ns("cpt"), "'] == 'biplot' "),
# box(width = 3, status = "primary",
# div(style="display: inline-block;vertical-align:top; width: 100px;",
# uiOutput(ns("cbiplot"))
# )
# )
# )
),
fluidRow(
box(width = 12, status = "primary",
plotOutput(ns("combination"))
)
)
)
}
makeResidualsUI <- function(id) {
ns <- NS(id)
tagList(
fluidRow(
box(status = "primary", width = 3,
radioButtons(ns("rpt"), "Plot",
c("Scores" = "scores",
"Loadings" = "loadings"),
selected = "scores")
),
box(width = 3, status = "primary",
div(style="display: inline-block;vertical-align:top; width: 100px;",
selectInput(ns("residual.pc1"),
"First PC",
choices = "",
selected = "")
),
div(style=
"display: inline-block;vertical-align:top; width: 20px;", ""),
div(style="display: inline-block;vertical-align:top; width: 100px;",
selectInput(ns("residual.pc2"),
"Second PC",
choices = "",
selected = "")
)
),
conditionalPanel(paste0("input['", ns("rpt"), "'] == 'scores' "),
box(width = 3, status = "primary",
selectInput(ns("colorlevels"),
label = "Color by factor",
choices = "",
selected = "")
)
)
),
fluidRow(
box(width = 12, status = "primary",
plotOutput(ns("residuals"))
)
)
)
}
#
# Server
#
ASCAmodel <- function(input, output, session, DAT.session) {
# List of all terms in the model.
# TermList has three elements: TermList$factors, TermList$interactions,
# and TermList$combinations
MakeTermsList <- function(input.string, fic) {
# Function make a list of terms to include in the model
# The function recognizes factor, interaction and combination input
# Input is checked on validity and for duplicate terms.
# interactions of combinations
# Args:
# Input:
# input.string: user input
# fic: character: f factor, i interaction, c combination
# Returns: checked.terms: list with terms to include
### Auxillary functions ###
CheckInteraction <- function(st) {
# Gets factors from an interaction
interacting.factors <- as.numeric(unlist(str_extract_all(st, "[0-9]+")))
# check for duplicate (eg. 2:2) and out of range factors
if(any(duplicated(interacting.factors)) |
any(interacting.factors > DAT.session$n.factors) |
any(interacting.factors <= 0)) {
return(NULL)
} else {
return(paste(sort(interacting.factors), collapse = ":"))
}
}
CheckFactors <- function(st) {
# Makes a comma separated list of factors from a range n-m
tmp.list <- str_extract_all(st, "[0-9]+")
from <- as.numeric(tmp.list[[1]][1])
to <- as.numeric(tmp.list[[1]][2])
if(length(tmp.list[[1]]) == 1) {
to <- from
}
fac.seq <- seq(from = from, to = to)
return(fac.seq[(fac.seq <= DAT.session$n.factors) & (fac.seq > 0)])
}
CheckCombinations <- function(st) {
# Check individual combinations
tmp.terms <- unique(unlist(sapply(st, function(x)
str_split(x, "\\+"), USE.NAMES = FALSE)))
factor.or.ineraction <- function(s) {
# check interaction or factor
if(grepl(":", s, fixed = TRUE)) {
res <- CheckInteraction(s)
} else {
res <- CheckFactors(s)
}
return(res)
}
combination <- unlist(lapply(tmp.terms, factor.or.ineraction))
return(paste(combination, collapse = "+"))
}
### Main code of MakeTermsList() ###
# Replace space as separater by ","
# Do this twice as the replacement works on pairs
# Allow for letter typo's, they are removed later on
tmp <- gsub("([a-zA-Z0-9]) +([a-zA-Z0-9])", "\\1,\\2", input.string)
tmp <- gsub("([a-zA-Z0-9]) +([a-zA-Z0-9])", "\\1,\\2", tmp)
# Remove remaining spaces
tmp <- gsub(" +", "", tmp)
# combinations
if(fic == "c") {
# get individal combinations
combinations <- unique(strsplit(tmp, ",", fixed = TRUE)[[1]])
tmp.terms <- unique(unlist(lapply(combinations, function(x)
str_extract_all(x,
"^([0-9]+)(:[0-9]+)*(\\+[0-9]+(:[0-9]+)*)+$")[[1]])
)
)
checked.terms <- lapply(tmp.terms, CheckCombinations)
# interactions
} else if(fic == "i") {
# extract interactions separated by ","
interactions <- unique(strsplit(tmp, ",", fixed = TRUE)[[1]])
# in case some non-numerics made it through
tmp.terms <- unique(unlist(lapply(interactions, function(x)
str_extract_all(x,
"^[0-9]+(:[0-9]+)+$")[[1]])
)
)
checked.terms <- as.list(unique(unlist(lapply(tmp.terms,
CheckInteraction))))
# factors
} else if(fic == "f") {
factors <- unique(strsplit(tmp, ",", fixed = TRUE)[[1]])
tmp.terms <- unique(unlist(lapply(factors, function(x)
str_extract_all(x,
"^[0-9]+([-][0-9])+$|^[0-9]+$")[[1]])
)
)
checked.terms <- as.list(
as.character(sort(unique(
unlist(
lapply(
tmp.terms, CheckFactors),
use.names = FALSE)
)
)
)
)
}
else { # No numbers
checked.terms <- list()
}
return(checked.terms)
}
MakeModelTerms <- function(f.list, i.list, c.list) {
# Makes the model from factors, interactions and combinations.
# In the model, the combination list is leading:
# if terms appear in both the combination list (c.list) and
# factor (f.list) or interaction list (i.list) they are remvoed
# from the latter two.
# Args:
# f.list: list with factors
# i.list: list with interactions
# c.list: list with combinations
# Returns:
# list(f.list, i.list, c.list): list with updated factors, interactions
# and combinations
# check for overlapping interactions
if(length(c.list) > 0 & length(i.list) > 0) {
# get interactions out
ints <- lapply(c.list, function(x)
unlist(str_extract_all(x, "[0-9]+(:[0-9]+)+"))
)
tmp.list <- lapply(i.list, function(x)
sapply(ints, function(y) any((x %in% y)))
)
mask <- lapply(tmp.list, function(x) Reduce("|", x))
i.list <- i.list[!unlist(mask)]
}
# check for overlapping factors
if(length(c.list) > 0 & length(f.list) > 0) {
# remove interactions
facs <- lapply(c.list, function(x) gsub("[0-9]+(:[0-9]+)+", "", x))
tmp.list <- lapply(facs,
function(x) unlist(str_extract_all(x, "[0-9]+"))
)
tmp.list <- lapply(f.list, function(x)
sapply(tmp.list, function(y) any((x %in% y)))
)
mask <- lapply(tmp.list, function(x) Reduce("|", x))
f.list <- f.list[!unlist(mask)]
}
return(list(f.list, i.list, c.list))
}
MakeCells <- function(col.nrs) {
# Select rows that belong to the same cell
# Args:
# col.nrs: vector with columns numbers from the design matrix.
# The columns are combined to make cells
# Returns:
# list: filled.cells: row assignments for each level
# levels: vector with for each row the levels
# create empty dataframe with same size as the data matrix
# Make selected columns of the design matrix numeric
design <- lapply(col.nrs, function(x)
as.numeric(DAT.session$design[, x])
)
design.matrix <- sapply(design, cbind)
# number of levels for each column
num.levels <- sapply(design, function(x) length(unique(x)))
# all level combinations
i.grid <- as.matrix(expand.grid(lapply(num.levels, seq)))
# Get matching rows from the design matrix
matching.rows <- lapply(seq(nrow(i.grid)), function(x)
which(sapply(seq(nrow(design.matrix)), function(y)
identical(design.matrix[y, ], as.numeric(i.grid[x, ])))
)
)
filled.cells <- matching.rows[sapply(matching.rows, function(x)
length(x) > 0)]
row.levels <- vector(length = nrow(design.matrix))
for(i in seq(length(filled.cells))) {
for(j in filled.cells[i]) {
row.levels[j] <- i
}
}
return(list(filled.cells, as.factor(row.levels)))
}
MakeCellAverages <- function(col.nrs) {
# Makes cell averages for all columns over selected rows
# Args:
# col.nrs: vector with columns numbers from the design matrix.
# The columns are combined to make cells and averages over the
# cells are calculated.
# Calls: MakeCells
# Returns:
# cell.averages: data frame with cell averages
# create empty dataframe with same size as the data matrix
cell.averages <- as.data.frame(matrix(integer(0),
nrow = dim(DAT.session$data)[1],
ncol = dim(DAT.session$data)[2])
)
filled.cells <- MakeCells(col.nrs)[[1]]
# collect the cell average in selected rows
for(x in filled.cells) {
# Note: use rbind to get a matrix out
cell.averages[x, ] <- as.data.frame(rbind(colMeans(DAT.session$data[x, ])))
}
return(cell.averages)
}
MakeFactorMatrix <- function(factor) {
matrix <- MakeCellAverages(as.numeric(factor))
overall.means.matrix <- matrix(rep(1, nrow(DAT.session$data)))%*%
colMeans(DAT.session$data)
factor.matrix <- matrix - overall.means.matrix
return(factor.matrix)
}
MakeInteractionMatrix <- function(interaction) {
# Makes interaction matrix from factors
# Args:
# interaction: interaction term (character string)
# Returns:
# interaction.matrix: list: matrix of the interaction
# Make all possible combinations with 'factors':
# A, B, c, AB, BC, AC, ABC
factors <- as.numeric(unlist(str_extract_all(
interaction, "[0-9]+"))
)
combinations <- lapply(seq(length(factors)), function(x)
combn(factors, x)
)
# Make matrix with level averages for all combinations
matrices <- lapply(combinations, function(x)
lapply(seq(ncol(x)), function(y)
MakeCellAverages(x[, y])
)
)
# Make interaction matrix by adding matrices
# with level averages with the right sign
# e.g. ABC - AB - AC - BC + A + B + C
interaction.matrix <- Reduce("+",
lapply(seq(
from = length(combinations), to = 1, by = -1),
function(x) ((-1)^(length(combinations) - x))*
Reduce("+", matrices[[x]])
)
)
overall.means.matrix <- matrix(rep(1, nrow(DAT.session$data)))%*%
colMeans(DAT.session$data)
# Add or subtract overall means from the interaction matrix
interaction.matrix <- interaction.matrix +
((-1)^(length(factors)))*overall.means.matrix
return(interaction.matrix)
}
MakeCombinationMatrix <- function(combination) {
MakeMatrix <- function(str) {
if(grepl(":", str)) {
matrix <- MakeInteractionMatrix(str)
} else {
matrix <- MakeFactorMatrix(str)
}
return(matrix)
}
# split on '+'
tmp.split <- unlist(strsplit(combination, "\\+" ))
matrix <- Reduce("+", lapply(tmp.split, function(x) MakeMatrix(x)))
return(matrix)
}
MakeResiduals <- function(model) {
# Make matrix with residuals
# Args:
# factors: factor matrices
# interactions: interaction matrices
# combinations: combination matrices
# data.df: scaled data matrix
# Returns:
# residuals: matrix with residuals
residuals <- DAT.session$data
residuals <- Reduce("-", init = residuals, model$means$matrices)
residuals <- Reduce("-", init = residuals, model$factors$matrices)
residuals <- Reduce("-", init = residuals, model$interactions$matrices)
residuals <- Reduce("-", init = residuals, model$combinations$matrices)
return(list(residuals))
}
##################################
MakeModel <- reactive({
req(DAT.session$data)
ASCA <- list()
# Terms
f.list <- MakeTermsList(input$include.factors, "f")
i.list <- MakeTermsList(input$include.interactions, "i")
c.list <- MakeTermsList(input$include.combinations, "c")
model.terms <- MakeModelTerms(f.list, i.list, c.list)
factors <- model.terms[[1]]
interactions <- model.terms[[2]]
combinations <- model.terms[[3]]
## Model ##
ASCA$data$ssq <- lapply(list(DAT.session$data), function(x)
sum(x^2)
)
# Overall means
ASCA$means$matrices <- list(matrix(rep(1, nrow(DAT.session$data)))%*%
colMeans(DAT.session$data))
ASCA$means$ssq <- lapply(ASCA$means$matrices, function(x)
sum(x^2)
)
# Factors
ASCA$factors$terms <- factors
ASCA$factors$matrices <- lapply(factors, function(x)
MakeFactorMatrix(x)
)
ASCA$factors$levels <- lapply(factors, function(x)
MakeCells(as.numeric(x))[[2]]
)
ASCA$factors$ssq <- lapply(ASCA$factors$matrices, function(x)
sum(x^2)
)
# Interactions
ASCA$interactions$terms <- interactions
ASCA$interactions$matrices <- lapply(interactions, function(x)
MakeInteractionMatrix(x)
)
ASCA$interactions$levels <- lapply(interactions, function(x)
MakeCells(as.numeric(unlist(
str_extract_all(x, "[0-9]+")))
)[[2]]
)
ASCA$interactions$ssq <- lapply(ASCA$interactions$matrices,
function(x) sum(x^2)
)
# Combinations
ASCA$combinations$terms <- combinations
ASCA$combinations$matrices <- lapply(combinations, function(x)
MakeCombinationMatrix(x)
)
ASCA$combinations$levels <- lapply(combinations, function(x)
MakeCells(as.numeric(unlist(
str_extract_all(x, "[0-9]+")))
)[[2]]
)
ASCA$combinations$ssq <- lapply(ASCA$combinations$matrices,
function(x) sum(x^2)
)
# Residuals
ASCA$residuals$terms <- lapply(seq(ncol(DAT.session$design)),
function(x) as.character(x))
ASCA$residuals$matrices <- MakeResiduals(ASCA)
ASCA$residuals$ssq <- lapply(ASCA$residuals$matrices, function(x)
sum(x^2)
)
## Model table ##
max.length <- max(length(factors), length(interactions),
length(combinations))
col.factors <- c(unlist(factors), rep("",
max.length - length(factors))
)
col.interactions <- c(unlist(interactions), rep("",
max.length - length(interactions))
)
col.combinations <- c(unlist(combinations), rep("",
max.length - length(combinations))
)
model.text <- cbind.data.frame(col.factors, col.interactions,
col.combinations)
colnames(model.text) <- c("Factors", "Interactions", "Combinations")
## Variance table
ssq.names <- c("Data", "Overall Means",
unlist(factors),
unlist(interactions),
unlist(combinations),
"Residuals")
ssq.values <- c(unlist(ASCA$data$ssq),
unlist(ASCA$means$ssq),
unlist(ASCA$factors$ssq),
unlist(ASCA$interactions$ssq),
unlist(ASCA$combinations$ssq),
unlist(ASCA$residuals$ssq))
ssq.percentages <- (ssq.values / unlist(ASCA$data$ssq))*100
ssq.table <- cbind.data.frame(ssq.names,
ssq.values,
ssq.percentages)
colnames(ssq.table) <- c("Source", "Sum of Squares",
"Percentage of variation")
DAT.session$models$ASCA <- ASCA
return(list(model.text, ssq.table))
})
SetPCs <- function(n.levels) {
# Set the values for the principal components, PC1 an PC2 that
# are plotted against each other
# Args:
# n.levels (numeric): maximum number of levels
# Returns:
# list:
# choices.pc1 (character): choices for first principal component
# selected.pc1 (character): selected first principal component
# choices.pc2 (character): choices for second principal component
# selected.pc1 (character): selected second principal component
if(n.levels == 2) { # two levels, single PC
choices.pc1 <- "1"
selected.pc1 <- "1"
choices.pc2 <- "None"
selected.pc2 <- "None"
} else if (n.levels > 2) { # more than 2 levels
choices.pc1 <- sapply(seq(n.levels - 1), as.character)
selected.pc1 <- choices.pc1[1]
choices.pc2 <- sapply(seq(n.levels - 1), as.character)
selected.pc2 <- choices.pc2[2]
}
return(list(choices.pc1, selected.pc1, choices.pc2, selected.pc2))
}
SelectPlotType <- function(pc1, pc2, wtp, plot.factor, plot.type,
plot.projections = "yes", x.values = 1,
group.by = 1, biplot.type = 1) {
# Makes scores, loadings and projections matrices and
# percentage explained for pc1 and pc2
# Args:
# pc1 (numeric): first principal component to plot
# pc2 (numeric): second principal component to plot (can be 0)
# wtp (character): what to plot, factor, interaction, combination or
# residuals
# plot.factor: (character): which factor/interaction/combination
# to plot
# Returns:
# All matrices returned are one (level plots) or two columns
# list:
# scores (dataframe): scores
# loadings (dataframe): loadings
# projections (dataframe): projections
# perc.explained (numeric): percentage explained variance by pc's for factor
# scores from svd-function are normalized
index <- which(DAT.session$models$ASCA[[wtp]]$terms ==
plot.factor)
svd.list <- svd(DAT.session$models$ASCA[[wtp]]$matrices[[index]])
u <- svd.list$u
d <- svd.list$d
v <- svd.list$v
scores.matrix <- u %*% diag(d)
residuals <- as.matrix(
DAT.session$models$ASCA$residuals$matrices[[1]])
if(pc2 != 0) {
scores <- scores.matrix[ , c(pc1, pc2)]
loadings <- v[ , c(pc1, pc2)]
projections <- residuals %*% loadings + scores
} else if(pc2 == 0) {
# add column of zeros to plot y = 0
scores <- cbind(scores.matrix[, pc1],
rep(0, nrow(scores.matrix)))
loadings <- cbind(v[, pc1], rep(0, nrow(v)))
projections <- residuals %*% loadings + scores
}
perc.explained <- 100*d^2 / sum((d)^2 )
pca.list <- list(as.data.frame(scores),
as.data.frame(loadings),
as.data.frame(diag(d)),
as.data.frame(projections),
perc.explained)
if(plot.type == "scores") {
p <- PlotScores(pc1, pc2, wtp, plot.factor, plot.projections, pca.list)
} else if (plot.type == "loadings") {
p <- PlotLoadings(pc1, pc2, wtp, plot.factor, pca.list)
} else if (plot.type == "levels") {
p <- PlotLevels(pc1, wtp, pca.list, x.values, group.by)
} else if (plot.type == "biplot") {
p <- PlotBiplot(pca.list, wtp, plot.factor, plot.projections,
pc1 = pc1, pc2 = pc2)
}
return(p)
}
Order.levels <- function(design.factor) {
# Order the design levels as the appear in the design file.
# Args:
# design.factor: ("character"): factor in design matrix
# Returns:
# ordered.levels: (factor): levels ordered as in design file
unique.levels <- unique(DAT.session$design[, as.numeric(design.factor)])
ordered.levels <- factor(DAT.session$design[, as.numeric(design.factor)],
levels = unique.levels)
return(ordered.levels)
}
PlotScores <- function(pc1, pc2, wtp, plot.factor, plot.projections,
pca.list) {
# Makes the score plots
# Args:
# pc1 (numeric): first principal component to plot
# pc2 (numeric): second principal component to plot (can be 0)
# wtp (character): what to plot, factor, interaction, combination or
# residuals
# plot.factor (character): plot factor: which factor, interaction or
# combination to plot
# plot.projections (character): if 'yes' projections are plotted
# pca.list: (list): scores, loadings, projections and precentage explained
# Returns:
# g (ggplot object): scores plot
scores <- pca.list[[1]]
loadings <- pca.list[[2]]
eigen.values <- pca.list[[3]]
projections <- pca.list[[4]]
perc.explnd <- pca.list[[5]]
if(wtp == "factors") {
color.to.plot <- Order.levels(plot.factor)
color.header <- colnames(DAT.session$design)[as.numeric(plot.factor)]
shape.to.plot <- as.factor(1)
shape.header <- ""
} else if(wtp == "interactions") {
# icolor is factor with color levels; ishape factor with shape levels
req(input$icolor, input$ishape)
color.to.plot <- Order.levels(input$icolor)
shape.to.plot <- Order.levels(input$ishape)
color.header <- colnames(DAT.session$design)[as.numeric(input$icolor)]
shape.header <- colnames(DAT.session$design)[as.numeric(input$ishape)]
} else if(wtp == "combinations") {
# ccolor is factor with color levels; cshape factor with shape levels
req(input$ccolor, input$cshape)
color.to.plot <- Order.levels(input$ccolor)
shape.to.plot <- Order.levels(input$cshape)
color.header <- colnames(DAT.session$design)[as.numeric(input$ccolor)]
shape.header <- colnames(DAT.session$design)[as.numeric(input$cshape)]
} else if(wtp == "residuals") {
index <- which(colnames(DAT.session$design) == input$colorlevels)
color.to.plot <- Order.levels(index)
shape.to.plot <- as.factor(1)
color.header <- input$colorlevels
shape.header <- ""
}
# Plot averages
g <- ggplot(data = scores, aes(x = scores[, 1], y = scores[, 2],
col = color.to.plot,
shape = shape.to.plot ))
g <- g + geom_point(size = 6)
# Plot projections. Note, the projections dataframe has only two columns
if(plot.projections == "yes") {
g <- g + geom_point(data = projections, aes(x = projections[, 1],
y = projections[, 2],
col = color.to.plot,
shape = shape.to.plot), size = 3)
}
x.label <- paste("PC", as.character(pc1),
"(", sprintf("%.2f", perc.explnd[pc1]),"%", ")",
sep = " ")
if(pc2 == 0) {
y.label <- ""
} else if (pc2 != 0) {
y.label <- paste("PC", as.character(pc2),
"(", sprintf("%.2f", perc.explnd[pc2]),"%", ")",
sep = " " )
}
g <- g + labs(title = "Scores",
x = x.label,
y = y.label)
if(wtp == "factors" | wtp == "residuals") {
g <- g + guides(shape = FALSE)
}
g <- g + scale_color_discrete(name = color.header)
g <- g + scale_shape_discrete(name = shape.header)
g <- g + theme(legend.text = element_text(size = 14),
legend.title = element_text(size = 16),
axis.title = element_text(size = 14),
plot.title = element_text(size = 16,
face="bold", hjust = 0.5)
)
return(g)
}
PlotLoadings <- function(pc1, pc2, wtp, plot.factor, pca.list) {
# Makes the loadings plot
loadings <- pca.list[[2]]
# Make dataframe with first column the variables,
if(pc2 == 0) {
plot.loadings <- cbind.data.frame(colnames(DAT.session$data),
loadings)
colnames(plot.loadings) <- c("Variable", "PC")
plot.title <- paste("Loadings PC", as.character(pc1))
p <- ggplot(data = plot.loadings,
aes(x = factor(Variable), y = PC) ) +
geom_bar(stat = "identity", fill = "#F8766D") +
labs(title = plot.title, x = "Variable", y = "Loadings")
} else {
req(pc1 != pc2)
plot.loadings <- cbind.data.frame(colnames(DAT.session$data),
loadings)
colnames(plot.loadings) <- c("Variable", as.character(pc1), as.character(pc2))
plot.loadings <- gather(plot.loadings, Loading, value,
c(as.character(pc1), as.character(pc2)))
plot.title <- paste("Loadings PC", as.character(pc1), "and PC",
as.character(pc2))
p <- ggplot(data = plot.loadings,
aes(x = factor(Variable), y = value, fill = Loading))
p <- p + geom_bar(stat = "identity", position = position_dodge(preserve = "total"))
p <- p + labs(title = plot.title, x = "Variable", y = "Loadings")
}
p <- p + theme(legend.text = element_text(size = 14),
legend.title = element_text(size = 16),
axis.title = element_text(size = 14),
axis.text.x = element_text(size = 14, angle = 90),
axis.text.y = element_text(size = 14),
plot.title = element_text(size = 16,
face="bold", hjust = 0.5)
)
return(p)
}
PlotLevels <- function(pc, wtp, pca.list, x.values, group.factor) {
# Plots PC-value against plot.levels and group by group.levels
scores <- pca.list[[1]]
perc.explnd <- pca.list[[5]]
x.values <- Order.levels(x.values)
group.by <- Order.levels(group.factor)
group.header <- colnames(DAT.session$design)[as.numeric(group.factor)]
if(wtp == "factors") {
g <- ggplot(data = scores, aes(x = x.values, y = scores[, 1],
col = "#F8766D" , group = 1))
g <- g + geom_line(size = 1)
g <- g + geom_point(size = 4)
g <- g + theme(legend.position = "none")
}
else {
g <- ggplot(data = scores, aes(x = x.values, y = scores[, 1],
col = group.by, group = group.by))
g <- g + geom_line(size = 1)
g <- g + geom_point(size = 4)
}
g <- g + scale_color_discrete(name = group.header)
g <- g + labs(title = "PC vs levels",
x = "Levels",
y = paste("PC", as.character(pc),
"(", sprintf("%.2f", perc.explnd[pc]),"%", ")",
sep = " " )
)
g <- g + theme(legend.text = element_text(size = 14),
legend.title = element_text(size = 16),
axis.title = element_text(size = 14),
axis.text.x = element_text(size = 14),
axis.text.y = element_text(size = 14),
plot.title = element_text(size = 16,
face="bold", hjust = 0.5)